Randomly unable to read IFormFile if use EnableBuffering
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
### Is there an existing issue for this?
- [x] 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 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_
Contributor guide
Assessment
This issue has not been assessed yet.