【问题标题】:Unsupported Media Types when POST to web apiPOST 到 web api 时不支持的媒体类型
【发布时间】:2017-10-20 19:23:26
【问题描述】:

这里是客户

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);

    }
}   

服务器

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

}  

我收到错误:

415 不支持的媒体类型

一直 - 此资源不支持请求实体的媒体类型“application/octet-stream”。我能做些什么呢?我在这里找到了一些已回答的主题,但没有帮助。

【问题讨论】:

    标签: asp.net rest asp.net-web-api


    【解决方案1】:

    虽然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);
    }
    

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

    还好有Response.Bodyhttps://github.com/danielearwicker/ByteArrayFormatters

    Response.ContentType = "application/octet-stream";
    Response.Body.Write(myArray, 0, myArray.Length);
    

    使你的控制器方法的返回类型void

    更新

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

    【讨论】:

    • 我正在使用 ASP.NET Core 2.2,仍然相关。
    猜你喜欢
    • 2016-11-26
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2014-02-13
    相关资源
    最近更新 更多