POST 到 web api 时不支持的媒体类型

Chr*_*nev 5 asp.net rest asp.net-web-api

这是客户端

using (var client = new HttpClient())
{

    client.BaseAddress = new Uri("http://localhost/MP.Business.Implementation.FaceAPI/");
    client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
    using (var request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress + "api/Recognition/Recognize"))
    {
        request.Content = new ByteArrayContent(pic);
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        await client.PostAsync(request.RequestUri, request.Content);

    }
}   
Run Code Online (Sandbox Code Playgroud)

服务器

[System.Web.Http.HttpPost]
public string Recognize(byte[] img)
{
    //do someth with the byte []

}  
Run Code Online (Sandbox Code Playgroud)

我收到错误:

415 不支持的媒体类型

一直 - 此资源不支持请求实体的媒体类型“应用程序/八位字节流”。我该怎么办?我在这里找到了一些已回答的主题,但没有帮助。

Dan*_*ker 5

虽然这byte[]是一种表示application/octet-stream数据的好方法,但 Web API 中默认情况并非如此。

我的解决方法是在 ASP.NET Core 1.1 中 - 其他变体中的细节可能有所不同。

在您的控制器方法中,删除该img参数。相反,请参阅Request.Body,它是一个Stream. 例如保存到文件:

using (var stream = new FileStream(someLocalPath, FileMode.Create))
{
    Request.Body.CopyTo(stream);
}
Run Code Online (Sandbox Code Playgroud)

从 GET 控制器方法返回二进制数据的情况类似。如果您指定返回类型,byte[]那么它将使用 base64 进行格式化!这使得它变得更大。现代浏览器完全能够处理原始二进制数据,因此这不再是明智的默认设置。

幸运的是,有一个Response.Body https://github.com/danielearwicker/ByteArrayFormatters

Response.ContentType = "application/octet-stream";
Response.Body.Write(myArray, 0, myArray.Length);
Run Code Online (Sandbox Code Playgroud)

设置控制器方法的返回类型void

更新

byte[]我创建了一个 nuget 包,可以在控制器方法中直接使用。请参阅: https: //github.com/danielearwicker/ByteArrayFormatters