的WebAPI传输字节数组为null数组、字节、WebAPI、null

2023-09-05 03:30:54 作者:伊人笑等鸳鸯醉°

我有一个是发送一个字节数组一个简单的客户端:

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

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

和接收的POST请求一个简单的服务器:

and a simple server that receives that post request:

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

问题是,我得到作为传入的参数。

你有一个想法是什么可能是这个问题?

Do you have an idea what can be the problem?

推荐答案

当你把参数的操作方法,你含蓄说你想要的格式化的一个序列化/反序列化的CLR对象。我是pretty的肯定,你不想让你的字节数组序列化为XML或JSON。我猜这同样适用于您的字符串的响应。

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") }
}

不幸的是,因为Content.ReadAsXXX方法都是异步,有必要使动作方法返回一个任务。你真的需要避免可能下ASP.NET管道被托管,因为你将导致死锁任何Web API的使用。结果和.Wait。

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.