【问题标题】:Getting "Cannot access a closed file" when trying to access form from httprequest尝试从 httprequest 访问表单时出现“无法访问已关闭的文件”
【发布时间】:2021-06-20 19:28:46
【问题描述】:

我正在尝试将 http post req 发送到包含表单数据中的图像的 azure httptrigger,但是当我尝试从 httptrigger 中访问 req.form 时,它显示“System.Private.CoreLib: Exception while执行函数:HttpTrigger。System.Private.CoreLib:无法访问已关闭的文件。” 当我打印 body 时,图像数据在那里,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

我花了几个小时试图找到答案,但我无法弄清楚。任何帮助将不胜感激。

【问题讨论】:

  • 请提供实际的代码片段,而不是图片,这对试图帮助您的人会更有帮助。

标签: c# azure httprequest multipartform-data azure-http-trigger


【解决方案1】:

我认为问题是您将正文阅读到最后,这将关闭流。之后,您可以在流关闭时访问 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);

【讨论】:

    猜你喜欢
    • 2019-12-04
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多