3

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?

Menelaos Vergis
  • 3,715
  • 5
  • 30
  • 46

1 Answers1

2

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.

Community
  • 1
  • 1
Tseng
  • 61,549
  • 15
  • 193
  • 205
  • So I don't have to remove session from a controller, I have register session only to the controllers who need it. – Menelaos Vergis Jul 25 '19 at 08:04
  • Basically yes. Not sure if you can remove it, thats the two approaches that instantly came to my mind – Tseng Jul 25 '19 at 08:05
  • I will test that later this day and accept the answer, thanks. – Menelaos Vergis Jul 25 '19 at 08:06
  • The middleware approach has the advantage that you can also apply it only on a single action of a Controller, i.e. if you have a stateless controller but one action may need a state, you could decorate the action with the attribute. It also runs after other middleware runs but before the action is called. Useful if you want to parse route data (which is not available before MVC middleware runs - that's true for ASP.NET 2.2 and prior; ASP.NET Core 3.x comes with new endpoint routing, making routing information available much earlier) – Tseng Jul 25 '19 at 08:29