【问题标题】:Posting multiple content types to web api将多种内容类型发布到 web api
【发布时间】:2014-03-08 12:50:25
【问题描述】:

我有一个 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;

Web api 方法签名如下所示:

public async Task<HttpResponseMessage> Post([FromBody]FeedItemParams parameters)

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

有什么想法我在这里出错了吗?

【问题讨论】:

    标签: c# asp.net-web-api content-type


    【解决方案1】:

    WebAPI 内置格式化程序仅支持以下媒体类型:application/jsontext/jsonapplication/xmltext/xmlapplication/x-www-form-urlencoded

    对于multipart/form-data,这是您发送的内容,请查看Sending HTML Form DataASP.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;
        }
    }
    

    如果您遵循第一篇文章,请使用示例控制器

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

    【讨论】:

    • 谢谢!事实证明,如果你想使用multipart/form-data,你需要从请求中拉出内容,因为正如你所说,web api 不会为你做这件事。不过,这是一个足够简单的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2014-06-08
    • 2012-08-13
    • 1970-01-01
    • 2019-10-16
    • 2017-08-28
    相关资源
    最近更新 更多