Sessionless controller in Asp.Net Mvc Core

823 Views Asked by At

I need to remove session from a controller because it adds unnecessarily load to my Redis server. I use Redis to store my session.

I have a controller that it's used from a Web-hook that its called rapidly and with high volume, the Web-hook doesn't use session and it would be better if I could completely remove the session from it.

As I google-searched I discover the attribute [ControllerSessionState] that removes the session from the controller but unfortunately it's only for Mvc3.

Is there something similar for Asp.Net Mvc Core?

1

There are 1 best solutions below

4
Tseng On BEST ANSWER

There are two basic approaches

Middleware filter

Create a base controller from which your stateful controllers inherit from and decorate it with an middleware filter attribute which registers a session.

Once created you'd have a base class

public class SessionPipeline
{
    public void Configure(IApplicationBuilder applicationBuilder)
    {
        applicationBuilder.UseSession();
    }
}

[MiddlewareFilter(typeof(SessionPipeline))]
public class StatefulControllerBase : ControllerBase
{
}

and have your stateful Controllers inherit from StatefulControllerBase instead of ControllerBase/Controller

Use MapWhen to conditionally register the Session

This approach was more common in the first versions of ASP.NET Core 1.x, but isn't much used these days

app.MapWhen(context => !context.Request.Path.StartsWith("/hooks/"), branch => 
{
    branch.UseSession();
});

This way session middleware will only be used for pathes not matching /hooks/ request path.