Skip to content

Randomly unable to read IFormFile if use EnableBuffering #64843

@UIT-AnhTu-0325

Description

@UIT-AnhTu-0325

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

When a simple middleware calls HttpRequest.EnableBuffering(), processing an uploaded file via IFormFile in later layers (controller, service, or any layer the IFormFile is passed through) can intermittently fail.
The failure occurs while reading the IFormFile stream and results in the following exception:
The inner stream position has changed unexpectedly.
This happens even though the middleware does not explicitly read or modify the request body, only enables buffering. The issue appears to be intermittent and is reproducible under normal request handling with multipart/form-data uploads.

Expected Behavior

Calling EnableBuffering() in middleware should not affect the ability to read IFormFile later in the request pipeline.

Steps To Reproduce

In Program.cs

app.Use(async (context, next) =>
{
    Console.WriteLine("Read the request from middleware!");
    context.Request.EnableBuffering();
    await next();
});

In WeatherForecastController.cs

[HttpPost]
public IActionResult Demo(IList<IFormFile> files)
{
    var tasks = files.Select(async (file) =>
    {
        try
        {
            Console.WriteLine("Read the file in request!");
            var mem = new MemoryStream();
            await file.CopyToAsync(mem);
            return file.FileName;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return null;
        }
    });

    var finalResult = Task.WhenAll(tasks);
    return Ok(finalResult);
}

Exceptions (if any)

The inner stream position has changed unexpectedly.

.NET Version

10.0.100

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions