how to redirect to new page after jquery ajax call in MVC if session timeout?

我的未来我决定 提交于 2019-12-03 03:20:31

An efficient way to handle a session expiry is to create a custom Authorization attribute and return a HTTP 403 response if the session has expired and were dealing with an ajax request.

To create an Ajax aware authorization attribute you can inherit from AuthorizeAttribute and override the HandleUnauthorizedRequest event with a check on the type of request eg. IsAjaxRequest()

public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // Fire back an unauthorized response
            filterContext.HttpContext.Response.StatusCode = 403;
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

Then just decorate your controllers or actions with the AjaxAuthorize attribute just as you normally would with Authorize

[AjaxAuthorize(Roles = "1,2,3,4,5")]
public class HomeController 
{

Then if you're using jQuery you can handle the 403 response by creating a global ajax error handler.

    $.ajaxSetup({
        error: function (x, e) {
            if (x.status == 403) {
                alert("Sorry, your session has expired. Please login again to continue");
                window.location = "/login";
            }
        }
    });

You can redirect user to login page on Session_Start event in Global

protected void Session_Start()
    {
        GeneRateKey();
        if (Session["Username"] != null)
        {
            //Redirect to Welcome Page if Session is not null  
            HttpContext.Current.Response.Redirect("~/WelcomeScreen", false);

        }
        else
        {
            //Redirect to Login Page if Session is null & Expires                   
            new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Login" } });
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!