简体   繁体   中英

ASP.NET MVC redirect to login page after session expires in AJAX

I just learning ASP.NET MVC and newbie in it so I can't find the solution for some problem. Maybe somebody faced this problem and can give me advice? Thanks for all!

In my project, I use ASP.NET Identity for authorization. The only problem I faced is how to redirect the user to login page after session expires. If action from controller called not from AJAX it works well, but if action called from AJAX function it crashes. I search for the solution, but everything I found not working for me. Now my code looks like:

Startup.cs

public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext<ApplicationContext>(ApplicationContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Login"),
                LogoutPath = new PathString("/Home/Login"),
                ExpireTimeSpan = TimeSpan.FromMinutes(1),

            });
        }

Web.config

<system.web>
    <authentication mode="Forms">
    <forms loginUrl="~/Home/Login"  timeout="1" />
    </authentication>
  </system.web>

Function from JS wich calls action:

function click(d) {
                //Some logic
                    $.ajax({
                        url: '@Url.Action("GetDataForNode", "Home")',
                        type: 'POST',
                        dataType: 'json',
                        cahe: false,
                        data: { uid: d.id, index: index, nodesUid: nodesUid, request },
                        success: function (results) {
                            //Some logic
                        },
                        error: function (xhr) {
                            if (xhr.status === 401) {
                                window.location.href = xhr.Data.LogOnUrl;
                                return;
                            }
                        }
                    })
            }

And in controller I created:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NotAuthorized",
                        LogOnUrl = FormsAuthentication.LoginUrl
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                filterContext.HttpContext.Response.End();

            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }

After executed I get this 在此处输入图片说明

Add a life cycle method Application_EndRequest handler to your code in global.asax.cs. Every request will end in this method, This method will allows you to redirect to appropriate action, when your request is unauthorized(401) just redirect to appropriate action.

   protected void Application_EndRequest()
        {                
            // redirected to the login page.
            var context = new HttpContextWrapper(Context);
            if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 401)
            {
                new RedirectResult("~/Account/Login");
            }
        }
    }

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