Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext .NET core saving instance in Middleware

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?

like image 738
Prem Avatar asked Aug 09 '16 15:08

Prem


People also ask

What is HttpContext in .NET Core?

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.

What happens when a terminal middleware is used in the request pipeline?

Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline.

How do I put middleware in NET Core?

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.

How can get HttpContext current in ASP.NET Core?

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.


1 Answers

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).

like image 100
Kévin Chalet Avatar answered Sep 19 '22 09:09

Kévin Chalet