问题描述
我正在尝试将 http post req 发送到包含表单数据中的图像的 azure httptrigger,但是当我尝试从 httptrigger 中访问 req.form 时,它显示“System.Private.CoreLib: Exception while执行函数:HttpTrigger。System.Private.CoreLib:无法访问关闭的文件。” 当我打印正文时,图像数据在那里,并且 req.HasFormContentType 返回 true,但是如果我尝试访问 req.Form,我会收到错误。
HTTP 触发器:
[FunctionName("AccessReceipts")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function,"get","post",Route = null)] HttpRequest req,ILogger log)
{
log.Loginformation("C# HTTP trigger function processed a request.");
//prints the body
using (StreamReader streamReader = new StreamReader(req.Body))
{
var requestBody = await streamReader.ReadToEndAsync();
log.Loginformation(requestBody);
}
//checks for form and attempts to access form from req
if (req.HasFormContentType)
{
log.Loginformation("There is a form.");
// Error happens here
var form = req.Form;
log.Loginformation("Form count is " + form.Count);
}
}
邮递员帖子: https://i.stack.imgur.com/iEHTN.png
输出: https://i.stack.imgur.com/E0u0B.png
我花了几个小时试图找到答案,但我无法弄清楚。任何帮助将不胜感激。
解决方法
我认为问题是您将正文读到最后,这将关闭流。然后在流关闭时访问 req.Form。
using (StreamReader streamReader = new StreamReader(req.Body))
{
var requestBody = await streamReader.ReadToEndAsync();
log.LogInformation(requestBody);
}
你可以试试这个:
String requestBody;
using (StreamReader streamReader = new StreamReader(req.Body))
{
requestBody = await streamReader.ReadToEndAsync();
log.LogInformation(requestBody);
}
dynamic requestBody = JsonConvert.DeserializeObject(requestBody);