尝试从 httprequest 访问表单时获取 "Cannot access a closed file"

Getting "Cannot access a closed file" when trying to access form from httprequest

我正在尝试将 http post 请求发送到包含表单数据中的图像的 azure httptrigger,但是当我尝试从 httptrigger 中访问 req.form 时,它显示“ System.Private.CoreLib:执行函数时出现异常:HttpTrigger。System.Private.CoreLib:无法访问已关闭的文件。” 当我打印正文时,图像数据在那里,并且 req.HasFormContentType returns 是正确的,但是如果我尝试访问 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);
        }
    }

邮递员post: 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);