简体   繁体   中英

Redirect to Login page after session expire or idle time in MVC application using ASP.net core C#

I am using ASP.NET Core. I want to redirect to login page when session expires or user is idle for 10 min. How can I achieve this? Currently, logout is happening (as when user clicks on any link or submits button, application gets redirect to login page. This happens when user clicks on button or link.) I want to redirect to happen to login page without user clicking on button or link.

Currently I have written this code in Startup.cs

  1. Inside ConfigureServices

     services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); }); services.AddMvc(options => options.EnableEndpointRouting = false); services.ConfigureApplicationCookie(options => { options.ExpireTimeSpan = System.TimeSpan.FromMinutes(10); options.SlidingExpiration = true; options.LoginPath = "/MVCApp/Login"; });
  2. In Configure

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

any suggestion on this.

you should handle this in client side like this:

<script>
(function() {

    const idleDurationSecs = 60;    // X number of seconds
    const redirectUrl = '/logout';  // Redirect idle users to this URL
    let idleTimeout; // variable to hold the timeout, do not modify

    const resetIdleTimeout = function() {

        // Clears the existing timeout
        if(idleTimeout) clearTimeout(idleTimeout);

        // Set a new idle timeout to load the redirectUrl after idleDurationSecs
        idleTimeout = setTimeout(() => location.href = redirectUrl, idleDurationSecs * 1000);
    };

    // Init on page load
    resetIdleTimeout();

    // Reset the idle timeout on any of the events listed below
    ['click', 'touchstart', 'mousemove'].forEach(evt =>
        document.addEventListener(evt, resetIdleTimeout, false)
    );

 })();
</script>

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