Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

asp.net web api - How to Get byte array properly from an Web Api Method in C#?

I have the following controller method:

[HttpPost]
[Route("SomeRoute")]
public byte[] MyMethod([FromBody] string ID)
{
  byte[] mybytearray = db.getmybytearray(ID);//working fine,returning proper result.
  return mybytearray;
}

Now in the calling method(thats also another WebApi method!) I have written like this:

private HttpClient client = new HttpClient ();
private HttpResponseMessage response = new HttpResponseMessage ();
byte[] mybytearray = null;
response = client.GetAsync(string.Format("api/ABC/MyMethod/{0}", ID)).Result;
if (response.IsSuccessStatusCode)
{
    mybytearray = response.Content.ReadAsByteArrayAsync().Result;//Here is the problem
} 

Now, the problem is the byte array MyMethod is sending is of 528 bytes, but here after making ReadAsByteArrayAsync, the size becomes larger(706 bytes) and the values are also goofed up.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually, HTTP can handle "raw" binary as well - the protocol itself is text based, but the payload can be binary (see all those files you download from the internet using HTTP).

There is a way to do this in WebApi - you just have to use StreamContent or ByteArrayContent as the content, so it does involve some manual work:

public HttpResponseMessage ReturnBytes(byte[] bytes)
{
  HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
  result.Content = new ByteArrayContent(bytes);
  result.Content.Headers.ContentType = 
      new MediaTypeHeaderValue("application/octet-stream");

  return result;
}

It may be possible to do the same thing using some attribute or something, but I don't know how.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...