Is it safe to store an instance of HttpContext in a middleware?
Example:
public class TestMiddleware
{
private readonly RequestDelegate next;
private HttpContext context;
public TestMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
this.context = context;
I would like to use it in other private methods to work on it, so I can either pass it around as parameter to those function or use it as shown in the example.
But is it thread safe?
HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received. The HttpContext instance is accessible by middleware and app frameworks such as Web API controllers, Razor Pages, SignalR, gRPC, and more.
Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline.
Search for word "middleware" in the top right search box as shown below. Select Middleware Class item and give it a name and click on Add button. This will add a new class for the middleware with extension method as shown below.
In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.
But is it thread safe?
No it's not, because middleware are necessarily singletons. If you store a specific HttpContext
in a shared field, it will be potentially reused during another request (which would be terrible).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With