2

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.

3 Answers 3

2

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?}");
        });
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Configure session in the ConfigureServices

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

2 Comments

Hello sir. I Also know about this but I just tell you how to change Session Time out from Controllers, not even Startup class
@RahulRathaur Found any solution? I also need this solution that you need.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.