gpt4 book ai didi

c# - 使用 .NET 5 Azure Functions 中的 Content-Type multipart/form-data 从 HttpRequestData 获取 POST 参数

转载 作者:行者123 更新时间:2023-12-02 23:37:29 27 4
gpt4 key购买 nike

我正在编写 Azure 函数,需要能够从 POST 请求正文中提取命名参数。然而,这并不是很简单,官方的例子或文件也从未表明这一点。我已经实现了自己的解决方案,但它对我来说效果不佳。

测试以下代码需要以下 NuGet 包:

我最远的距离如下:

/* Azure Function, HTTP Trigger, .NET 5 : Update.cs */
[Function("Update")]
public static Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")]
HttpRequestData req,
FunctionContext executionContext)
{
//Get body of request
StreamContent contentStream = new StreamContent(req.Body);

//Get POST agruments out of multipart/form-data body into a dictionary
Dictionary<string, string> dictionary = new Dictionary<string, string>();
{
MultipartMemoryStreamProvider multipart = await stream.ReadAsMultipartAsync();
for (int i = 0; i < multipart.Contents.Count; i++)
{
NameValueCollection collection = await multipart.Contents[i].ReadAsFormDataAsync();
foreach (string key in collection.Keys) dictionary.Add(key, collection[key]);
}
}
//Exception thrown in last logical unit!
contentStream.Dispose();
return result;
}
System.ArgumentException: Invalid 'HttpContent' instance provided. It does not have a content-type header value. 'HttpContent' instances must have a content-type header starting with 'multipart/'. (Parameter 'content')
at System.Net.Http.Formatting.Parsers.MimeMultipartBodyPartParser.ValidateArguments(HttpContent content, Int64 maxMessageSize, Boolean throwOnError)
at System.Net.Http.Formatting.Parsers.MimeMultipartBodyPartParser..ctor(HttpContent content, MultipartStreamProvider streamProvider, Int64 maxMessageSize, Int32 maxBodyPartHeaderSize)
at System.Net.Http.Formatting.Parsers.MimeMultipartBodyPartParser..ctor(HttpContent content, MultipartStreamProvider streamProvider)
at System.Net.Http.HttpContentMultipartExtensions.ReadAsMultipartAsync[T](HttpContent content, T streamProvider, Int32 bufferSize, CancellationToken cancellationToken)

我不明白为什么会抛出此异常,因为在调试器中观察 req 变量的值会显示 Headers 属性中的以下项目:

multipart/form-data; boundary=--------------------------4784986464564849849262

我愿意修复我的代码,有另一个解决方案,或者指向正确的方向。

最佳答案

只需将正文读取为文本,然后根据需要进行处理(例如转换为 json):

        StreamReader reader = new StreamReader(req.Body);
string text = reader.ReadToEnd();

关于c# - 使用 .NET 5 Azure Functions 中的 Content-Type multipart/form-data 从 HttpRequestData 获取 POST 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69023205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com