简体   繁体   中英

Sessionless controller in Asp.Net Mvc Core

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM