415 POST 到 .NET Web API 上不支持的媒体类型

415 Unsupported Media Type on POST to .NET Web API

我有一种将图像发布到网络的方法 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。显然这里缺少一些东西,但我无法将这些点联系起来。有什么想法吗?

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