我正在调整最近在.NET Standard中启动的项目以使用Azure Functions。我有一个HTTP触发器,我直接从表单发布。只有两个字段:数字输入和文件上传。
在不引用任何其他库的情况下使用该函数时,我无法在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时也会发生这种情况。
答案 0 :(得分:4)
据我所知," ReadAsFormDataAsync"方法只接受" application / x-www-form-urlencoded"内容类型。它不支持获取多部分/表格数据'内容类型。
因此,如果你想发送多个竞赛部分,你需要使用" ReadAsMultipartAsync"方法
有关如何使用" ReadAsMultipartAsync"的更多细节在azure函数中的方法,你可以参考这个代码:
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);
}
结果:
答案 1 :(得分:0)
您是否尝试过在HTTP请求标头上将内容类型设置为JSON?
Content-Type=application/json