Azure函数-如何读取表单数据 [英] Azure functions - How to read form data

查看:54
本文介绍了Azure函数-如何读取表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Azure函数中读取表单数据?我尝试了几种方法,但是总是出现错误,例如:

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

错误: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'.

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'.

我检查了请求内容,并以multipart/form-data的身份收到请求:

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"

谢谢您的提示.

推荐答案

由于请求包含"application/x-www-form-urlencoded"类型的内容,因此您需要将输入转换为NameValueCollection才能读取输入:

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

这篇关于Azure函数-如何读取表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆