Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi transfer byte array is null

I have a simple client that is sending a byte array:

var content = new ByteArrayContent(wav);
httpClient.PostAsync(@"http://localhost:12080/api/values", content);

and a simple server that receives that post request:

[HttpPost]
    public string Post([FromBody]byte[] parms)
    {
        //bla bla
    }

the problem is that I getting null as the incoming parameter.

Do you have an idea what can be the problem?

like image 483
Guy Dubrovski Avatar asked Mar 29 '14 06:03

Guy Dubrovski


1 Answers

When you put parameters in the Action method, you are implicitly saying that you want one of the formatters to "serialize/deserialize" the CLR object. I'm pretty sure you don't want your byte array serialized as XML or JSON. I'm guessing the same goes for your string response.

For primitives like stream, string and byte arrays you simply do this,

[HttpPost]
public async Task<HttpResponseMessage> Post()
{
    byte[] parms = await Request.Content.ReadAsByteArray();

    return new HttpResponseMessage { Content=StringContent("my text/plain response") }
}

Unfortunately, because the Content.ReadAsXXX methods are all async, it is necessary to make the Action method return a Task. You really need to avoid using .Result and .Wait in any Web API that might be hosted under an ASP.NET pipeline because you will cause deadlocks.

like image 81
Darrel Miller Avatar answered Sep 30 '22 18:09

Darrel Miller