How to Get byte array properly from an Web Api Method in C#?

前端 未结 7 1193
故里飘歌
故里飘歌 2020-11-30 01:49

I have the following controller method:

[HttpPost]
[Route("SomeRoute")]
public byte[] MyMethod([FromBody] string ID)
{
  byte[] mybytearray = db.get         


        
7条回答
  •  甜味超标
    2020-11-30 02:25

    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.

提交回复
热议问题