Search code examples
c#azurehttprequestmultipartform-dataazure-http-trigger

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


I'm trying to send an http post req to an azure httptrigger containing an image in form data, but when I attempt to access the req.form from within the httptrigger, it says "System.Private.CoreLib: Exception while executing function: HttpTrigger. System.Private.CoreLib: Cannot access a closed file." When I print the body, the image data is there, and req.HasFormContentType returns true, but if I try to access req.Form, I get the error.

HTTP Trigger:

[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);
        }
    }

Postman post: https://i.sstatic.net/iEHTN.png

Output: https://i.sstatic.net/E0u0B.png

I spent a couple hours trying to find answers but I couldn't figure it out. Any help would be very much appreciated.


Solution

  • I would assume issue is that you read body to the end and this will close stream. And after that you access req.Form while stream is closed.

     using (StreamReader streamReader = new StreamReader(req.Body))
        {
            var requestBody = await streamReader.ReadToEndAsync();
            log.LogInformation(requestBody);
        }
    

    You can try this:

    String requestBody;
    using (StreamReader streamReader = new StreamReader(req.Body))
    {
                requestBody = await streamReader.ReadToEndAsync();
                log.LogInformation(requestBody);
    }
    dynamic requestBody = JsonConvert.DeserializeObject(requestBody);