0

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.stack.imgur.com/iEHTN.png

Output: https://i.stack.imgur.com/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.

Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80
  • 1
    Instead of images please provide actual code pieces, that'll be more helpful to someone who's trying to help you. – Mihir Dave Mar 24 '21 at 06:21

1 Answers1

0

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);
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80