2017-08-29 63 views
0

我正在修改最近在.NET Standard中啓動的項目以使用Azure函數。我有一個HTTP觸發器,我直接從窗體發佈到。只有兩個字段:數字輸入和文件上傳。沒有MediaTypeFormatter可用於從媒體類型爲'multipart/form-data'的內容讀取類型爲'HttpRequestMessage'的對象

在不引用任何其他庫的情況下使用該函數時,我無法在HttpRequestMessage上使用ReadAsFormDataAsync。我收到一個:

System.Net.Http.UnsupportedMediaTypeException: No MediaTypeFormatter is 
available to read an object of type 'FormDataCollection' from content with 
media type 'multipart/form-data'. 

我可以使用ReadAsMultipartAsync並設法獲取發佈值。

當我引用.NET庫的標準,雖然,我甚至無法進入,因爲它被完全拒絕的功能:

System.Net.Http.UnsupportedMediaTypeException: No MediaTypeFormatter is 
available to read an object of type 'HttpRequestMessage' from content with 
media type 'multipart/form-data' 

我試圖創建一個全新的骨架.NET標準庫和引用這一點,一樣。

作爲附加參考,我發現this post,但我似乎沒有相同的問題。

打算提出問題,但決定先在這裏嘗試。有任何想法嗎?

編輯:當enctype是application/x-www-form-urlencoded時,也會發生這種情況。

回答

1

據我所知,「ReadAsFormDataAsync」方法只接受「application/x-www-form-urlencoded」類型的內容。它不支持獲取'multipart/form-data'類型的內容。

所以如果你想發送比賽的多個部分,你需要使用「ReadAsMultipartAsync」方法。

更多有關如何在蔚藍的函數中使用「ReadAsMultipartAsync」方法的詳細信息,你可以參考這個代碼:

using System.Net; 
using System.Net.Http; 
using System.IO; 
using System.Collections.Specialized; 

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) 
{ 
    log.Info("C# HTTP trigger function processed a request."); 
    string result = "- -"; 
      if (req.Content.IsMimeMultipartContent()) 
      { 
       var provider = new MultipartMemoryStreamProvider(); 
       req.Content.ReadAsMultipartAsync(provider).Wait(); 
       foreach (HttpContent ctnt in provider.Contents) 
       { 
        //now read individual part into STREAM 
        var stream = ctnt.ReadAsStreamAsync(); 
        return req.CreateResponse(HttpStatusCode.OK, "Stream Length " + stream.Result.Length); 

         using (var ms = new MemoryStream()) 
         { 
          //do something with the stream 
         } 

       } 
      } 
      if (req.Content.IsFormData()) 
      { 
       NameValueCollection col = req.Content.ReadAsFormDataAsync().Result; 
       return req.CreateResponse(HttpStatusCode.OK, $" {col[0]}"); 
      } 

      // dynamic data = await req.Content.ReadAsFormDataAsync(); 

      // Fetching the name from the path parameter in the request URL 
      return req.CreateResponse(HttpStatusCode.OK, "Doesn't get anything " + result); 
} 

結果:

enter image description here

+0

我應該在原來的職位已經注意到這種情況也發生在enctype上。我將編輯添加。 – Dexterity

+0

在我身邊,我可以得到application/x-www-form-urlencoded請求。如果可能的話,請發佈整個天藍色的函數http觸發代碼,您現在使用。 –

+0

[使用functionName( 「TestPost」)] 公共靜態異步任務運行([HttpTrigger(AuthorizationLevel.Anonymous, 「後」)] HttpRequestMessage REQ,TraceWriter日誌) { 動態數據=等待req.Content.ReadAsAsync (); string name = data?.name; return req.CreateResponse(HttpStatusCode.Created); } } 函數沒有進入,因爲它失敗,出現以下情況:異常綁定參數'req'和另一個錯誤:沒有MediaTypeFormatter可用於從媒體類型爲'application/x-www的內容中讀取類型爲'HttpRequestMessage'的對象 - 形式進行了urlencoded」。 – Dexterity

相關問題