微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试从 httprequest 访问表单时出现“无法访问关闭的文件”

如何解决尝试从 httprequest 访问表单时出现“无法访问关闭的文件”

我正在尝试将 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。