簡體   English   中英

將多種內容類型發布到Web API

[英]Posting multiple content types to 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;

Web api方法簽名如下所示:

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

運行此命令時,出現UnsupportedMediaType異常。 我知道這與ObjectContent ,因為當我在查詢字符串中僅傳遞ID而不是正文中的對象時,此方法有效。

有什么想法我要在這里出錯嗎?

WebAPI內置格式化程序僅支持以下媒體類型: application/jsontext/jsonapplication/xmltext/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;
    }
}

如果您遵循第一篇文章,請參閱示例控制器

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM