Azure functions - How to read form data

旧时模样 提交于 2020-05-12 02:49:04

问题


How to read form data in Azure functions? I tried to do it in several ways, but always I get an error, eg.:

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    dynamic data = await req.Content.ReadAsFormDataAsync();

    return req.CreateResponse(HttpStatusCode.OK, $" {data}");
}

Error: Exception while executing function: Functions.FormTrigger. System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'application/json'.

I checked request content and I'm getting request as multipart/form-data:

" ------WebKitFormBoundary47wKq7pk9Fcc4H9J\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nsdgs\r\n
------WebKitFormBoundary47wKq7pk9Fcc4H9J\r\nContent-Disposition: form-data; name=\" _replyto\"\r\n\r\nsdg@sdg.com\r\n
------WebKitFormBoundary47wKq7pk9Fcc4H9J\r\nContent-Disposition: form-data; name=\"message\"\r\n\r\nsdgsd\r\n
------WebKitFormBoundary47wKq7pk9Fcc4H9J--\r\n"

Thank you for any hints.


回答1:


As the request contains "application/x-www-form-urlencoded" type of contents, you need to convert the input to NameValueCollection in order to read input:

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

You can also pass Key string instead of Index which would make the code more readable and self-explanatory




回答2:


In order to read form data, there is the method ReadAsMultipartAsync:

data = await req.Content.ReadAsMultipartAsync().ConfigureAwait(false);


来源:https://stackoverflow.com/questions/41160504/azure-functions-how-to-read-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!