IFeatureCollection has been disposed when trying to access HttpContext.Request.Headers
See original GitHub issueSteps to reprodce
- Create a simple API ASP.NET Core 3.1 Web Application using Visual Studio 2019 template.
- In the handler method, add access to HttpContext.Request.Headers.
- Create a REST client that sends many requests simultaneously.
The result is that eventually, a System.ObjectDisposedException will be thrown upon accessing HttpContext.Request.Headers.
Startup code
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<WeatherForecastController>();
services.AddMvc().AddControllersAsServices();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Controller code
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var headers = HttpContext.Request.Headers;
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
Client code
static void Main(string[] args)
{
Parallel.For(0, 3000, i =>
{
var getWeatherUri = new Uri("https://localhost:44341/weatherforecast");
MediaTypeWithQualityHeaderValue requestHeader = new MediaTypeWithQualityHeaderValue("application/json");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(requestHeader);
var response = client.GetAsync(getWeatherUri.AbsoluteUri).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception($"{response.StatusCode}: {response.RequestMessage} | {response.ReasonPhrase}");
}
});
}
Further technical details
-
Exception details: System.ObjectDisposedException HResult=0x80131622 Message=IFeatureCollection has been disposed. Object name: ‘Collection’. Source=Microsoft.AspNetCore.Http.Features StackTrace: at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ThrowContextDisposed() in /_/src/Http/Http.Features/src/FeatureReferences.cs:line 120
-
ASP.NET Core version - 3.1.0
-
Output of
dotnet --info
: dotnetInfo.txt -
The IDE is VS2019 Version 16.4.1
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:7 (4 by maintainers)
Top Results From Across the Web
IFeatureCollection has been disposed. in Asp.net Core ...
Scoped services are disposed at the request's end. The main problem is OnChanged can be called after the request's end.
Read more >IFeatureCollection has been disposed when trying to ...
IFeatureCollection has been disposed when trying to access HttpContext.Request.Headers · Issue... Steps to reprodce Create a simple API ASP.NET ...
Read more >ObjectDisposedException in .NET Core middleware with ...
I seem to either get System.InvalidOperationException: An attempt was made to use the context while it is being configured. or System.
Read more >IFeatures Collection has been disposed, object Name
Hi Dear All, i have created a web api project and created a new web api named login, now i created asp.net core...
Read more >IFeatureCollection Interface (Microsoft.AspNetCore.Http. ...
Incremented for each modification and can be used to verify cached results. Methods. Get<TFeature>(). Retrieves the requested feature from the collection.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I checked with MVC and controllers are not supported as singletons. They have request state, so even if you didn’t hit issues like this, you’d still have concurrency problems.
@Tratcher, @anurse Thank you for your help!