【问题标题】:415 Unsupported Media Type on POST to .NET Web API415 POST 到 .NET Web API 上的媒体类型不受支持
【发布时间】:2018-02-16 08:55:56
【问题描述】:

我有一个将图像发布到 Web API 的方法。但是,我一直收到 HTTP 错误 415 Unsupported Media Type。

我的宿主方法如下所示:

[HttpPost]
[Route("Image/Post")]
public HttpResponseMessage Post(Image image)
{
  // do stuff
  return Request.CreateResponse(HttpStatusCode.Created);
}

在我的调用方法中,我有这样的代码:

string url = String.Concat(this.WebApiUrl, "Image/Post");
HttpContent original = new ByteArrayContent(ImageUtility.ImageToByteArray(image));
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
HttpResponseMessage response = client.PostAsync(url, original).Result;
response.EnsureSuccessStatusCode();

ImageToByteArray() 方法供参考:

public static byte[] ImageToByteArray(Image image)
{
    if (image == null) {throw new ArgumentNullException("image"); }
    using (MemoryStream ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        return ms.ToArray();
     }
}

当我调用 client.PostAsync().Result 时,我得到 415。显然这里缺少一些东西,但我无法连接这些点。有什么想法吗?

【问题讨论】:

  • 那么接收端是如何反序列化图像的呢?有效载荷是什么内容类型?
  • 这是一张 JPEG 图片。
  • 所以将HttpClient发出的请求的content-type设置为image/jpeg。现在,一旦图像到达服务器,您实际上想对它做什么?您真的要实例化 Image 还是只使用请求流中的字节?
  • 我尝试插入 "original.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");"但这无济于事。
  • 图片将被插入数据库,该方法返回一个id。

标签: c# .net http asp.net-web-api2


【解决方案1】:

WebApi 无法将图像字节流绑定到 Image 实例。最好接受这是二进制数据并采取相应措施。

IIRC,你可以收到这样的请求正文:

public async Task<HttpResponseMessage> Post()
{
    var requestStream = await Request.Content.ReadAsStreamAsync();
    var contentType = Request.Content.Headers.ContentType;
    //store content-type and contents of requestStream
    return Request.CreateResponse(HttpStatusCode.Created);
}

确保在发送端设置content-type

【讨论】:

  • 谢谢。这似乎奏效了!我会做更多的测试。
  • 这解决了我如何将二进制对象发布到 Web API,并在托管方法中接收它的问题。感谢您的帮助!
猜你喜欢
  • 2015-06-02
  • 2016-11-26
  • 2020-09-03
  • 2019-07-28
  • 2015-06-17
  • 1970-01-01
  • 2017-09-14
  • 2020-09-25
  • 2017-10-20
相关资源
最近更新 更多