Rahul Rathaur
Rahul Rathaur

Reputation: 30

Add session timeout from controller in ASP.NET Core MVC

How to add session timeout from a controller in ASP.NET Core MVC?

I am working on an ASP.NET Core MVC web application, and I need to add the session timeout from my controller's action method.

Upvotes: 2

Views: 2864

Answers (3)

spalMcc
spalMcc

Reputation: 41

Use the following code (we have forms authentication in this application .NET6 ASP.NET MVC)

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
     .AddCookie(options =>
     {
         options.LoginPath = "/Account/Login";
         options.ExpireTimeSpan = TimeSpan.FromSeconds(15);
         options.Cookie.HttpOnly = true;
         options.Cookie.IsEssential = true;
     });

This will work as I found this solution 1 day ago.

Upvotes: 1

Xueli Chen
Xueli Chen

Reputation: 12695

You could try to customize a middleware filter attribute which registers a session, and decorate the controller or the action with this:

public class SessionPipeline
{
    public void Configure(IApplicationBuilder applicationBuilder)
    {
        var options = new SessionOptions
        {
            IdleTimeout = TimeSpan.FromSeconds(5),
        };
        applicationBuilder.UseSession(options);
    }
}

[MiddlewareFilter(typeof(SessionPipeline))]
public class HomeController : Controller
{
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddSession();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //...more middlewares

        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Upvotes: 2

junlan
junlan

Reputation: 261

Configure session in the ConfigureServices

 services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromSeconds(120);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

Upvotes: 1

Related Questions