将多种内容类型发布到web api

Ela*_*hmi 1 c# content-type asp.net-web-api

我有一个web api,我想发布一个图像文件+一些数据,以便在服务器收到它时正确处理它.

调用代码看起来像这样:

using(var client = new HttpClient())
using(var content = new MultipartFormDataContent())
{
  client.BaseAddress = new Uri("http://localhost:8080/");
  var fileContent = new ByteArrayContent(File.ReadAllBytes(fileName));
  fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
   {
     FileName = "foo.jpg"
   };

   content.Add(fileContent);
   FeedItemParams parameters = new FeedItemParams()
   {
     Id = "1234",
     comment = "Some comment about this or that."
   };
   content.Add(new ObjectContent<FeedItemParams>(parameters, new JsonMediaTypeFormatter()), "parameters");
   content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");

   var result = client.PostAsync("/api/ImageServices", content).Result;
Run Code Online (Sandbox Code Playgroud)

web api方法签名如下所示:

public async Task<HttpResponseMessage> Post([FromBody]FeedItemParams parameters)
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到一个UnsupportedMediaType例外.我知道这与此有关ObjectContent,因为当我ID在查询字符串中传递一个而不是正文中的对象时,此方法有效.

我在这里出错的任何想法?

Los*_*ter 8

的WebAPI内置格式化仅支持以下介质类型:application/json,text/json,application/xml,text/xmlapplication/x-www-form-urlencoded

对于multipart/form-data您发送的内容,请查看发送HTML表单数据ASP.NET WebApi:MultipartDataMediaFormatter

样本客户端

using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        client.BaseAddress = new Uri("http://localhost:54711/");

        content.Add(new StreamContent(File.OpenRead(@"d:\foo.jpg")), "foo", "foo.jpg");

        var parameters = new FeedItemParams()
        {
            Id = "1234",
            Comment = "Some comment about this or that."
        };
        content.Add(new ObjectContent<FeedItemParams>(parameters, new JsonMediaTypeFormatter()), "parameters");

        var result = client.PostAsync("/api/Values", content).Result;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您按照第一篇文章进行样本控制

public async Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    // Read the form data.
    await Request.Content.ReadAsMultipartAsync(provider);

    //use provider.FileData to get the file
    //use provider.FormData to get FeedItemParams. you have to deserialize the JSON yourself

    return Request.CreateResponse(HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)