Handling session timeout in ajax calls
我正在使用jquery对asp.net mvc控制器动作进行ajax调用:
1 2 3 4 5 6 | [AcceptVerbs(HttpVerbs.Post)] public ActionResult GetWeek(string startDay) { var daysOfWeek = CompanyUtility.GetWeek(User.Company.Id, startDay); return Json(daysOfWeek); } |
当会话超时时,此调用将失败,因为User对象存储在会话中。我创建了一个自定义authorize属性,以检查会话是否丢失并重定向到登录页面。这适用于页面请求,但它不适用于ajax请求,因为您无法从ajax请求重定向:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorizeUserAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!httpContext.Request.IsAjaxRequest()) {//validate http request. if (!httpContext.Request.IsAuthenticated || httpContext.Session["User"] == null) { FormsAuthentication.SignOut(); httpContext.Response.Redirect("~/?returnurl=" + httpContext.Request.Url.ToString()); return false; } } return true; } } |
我在另一个线程上读到,当用户未经过身份验证并且你发出ajax请求时,你应该将状态代码设置为401(未授权),然后在js中检查它并将它们重定向到登录页面。但是,我不能让这个工作:
1 2 3 4 5 6 7 8 9 10 11 | protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (Request.IsAjaxRequest() && (!Request.IsAuthenticated || User == null)) { filterContext.RequestContext.HttpContext.Response.StatusCode = 401; } else { base.OnActionExecuting(filterContext); } } |
基本上,它将它设置为401,但随后它将继续进入控制器操作并抛出一个对象引用未设置为对象错误的实例,然后将错误500返回给客户端js。如果我更改我的自定义Authorize属性以验证ajax请求并为未经过身份验证的那些返回false,则会使ajax请求返回我的登录页面,这显然不起作用。
我该如何工作?
您可以编写一个自定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class MyAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new JsonResult { Data = new { // put whatever data you want which will be sent // to the client message ="sorry, but you were logged out" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } else { base.HandleUnauthorizedRequest(filterContext); } } } |
然后用它和客户端装饰你的控制器/动作:
1 2 3 4 5 6 7 | $.get('@Url.Action("SomeAction")', function (result) { if (result.message) { alert(result.message); } else { // do whatever you were doing before with the results } }); |
我不会将JsonRequestBehavior更改为AllowGet。相反,我建议:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public sealed class MyAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); OnAuthorizationHelp(filterContext); } internal void OnAuthorizationHelp(AuthorizationContext filterContext) { if (filterContext.Result is HttpUnauthorizedResult) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.End(); } } } } |
并添加全局js ajax错误处理程序:
1 2 3 4 5 | $(document).ajaxError(function (xhr, props) { if (props.status === 401) { location.reload(); } } |
虽然这已经过去了,但我认为如果您使用的是.NET 4.5,这是最简短和最甜蜜的答案。添加了名为SuppressFormsAuthenticationRedirect的小属性。设置为true,它不会执行302重定向登录页面。
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.suppressformsauthenticationredirect.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AjaxAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // returns a 401 already base.HandleUnauthorizedRequest(filterContext); if (filterContext.HttpContext.Request.IsAjaxRequest()) { // we simply have to tell mvc not to redirect to login page filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; } } } |
假设您计划处理ajax请求失败/错误回调,其中您将获得401 Unauthorized。
在Master页面上添加这个jquery脚本------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <script type="text/javascript"> $.ajaxSetup({ statusCode: { 403: function () { window.location.reload(); } } }); OR $.ajaxSetup({ error: function (x, e) { if (x.status == 403) { window.location.reload(); } } }); |
在项目中添加一个以TraceFilter命名的cs文件,并编写一个继承到ActionFilterAttribute的封装类TraceFilterAttribute。
通过写下面的行,在项目的App_Start文件夹中的FilterConfig.cs中添加TraceFilterAttribute类。
filters.Add(new TraceFilterAttribute());
在TraceFilterAttribute类中重写方法OnActionExecuting()。这将自动检查会话,如果找到会话null,则调用母版页中可用的脚本,然后您可以转到您的选择页面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | [AttributeUsage(AttributeTargets.All)] public sealed class TraceFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext != null) { HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session; var userSession = objHttpSessionStateBase["etenetID"]; if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession)) { objHttpSessionStateBase.RemoveAll(); objHttpSessionStateBase.Clear(); objHttpSessionStateBase.Abandon(); if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 403; filterContext.Result = new JsonResult { Data ="LogOut" }; } else { filterContext.Result = new RedirectResult("~/Admin/GoToLogin"); } } } } } |
我遇到了类似的问题并发现了这一点
在发送响应之前,不要返回任何JSON,而是强制ASP.NET返回401代码。在
1 2 3 4 5 6 7 8 9 10 | protected void Application_EndRequest() { var context = new HttpContextWrapper(Context); if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 302) { Context.Response.Clear(); Context.Response.Write("**custom error message**"); Context.Response.StatusCode = 401; } } |
然后你可以让客户端用JavaScript / jQuery或者你正在使用的任何东西来处理它
这是我如何在我的自定义授权中以如此简单的方式处理这个问题,我检查会话是否已经出来并使用布尔值处理未经授权的处理,以检查它是否真的经过身份验证但未经授权(重定向到未授权的页面)或者由于会话超时而未经过身份验证(重定向到登录)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | private bool ispha_LoggedIn = false; protected override bool AuthorizeCore(HttpContextBase httpContext) { ispha_LoggedIn = false; var session = httpContext.Session; bool authorize = false; if (httpContext.Session["authenticationInfo"] == null) { return authorize; } using (OrchtechHR_MVCEntities db = new OrchtechHR_MVCEntities()) { UserAuthenticationController UM = new UserAuthenticationController(); foreach (var roles in userAssignedRoles) { authorize = UM.IsUserInRole(httpContext.User.Identity.Name, roles); if (authorize) { return authorize; } } } ispha_LoggedIn = true; return authorize; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (ispha_LoggedIn==false) { filterContext.Result = new RedirectResult("~/UserAuthentication/LogIn"); } else { filterContext.Result = new RedirectResult("~/Dashboard/UnAuthorized"); } } |
希望如果这引导某人,请尽管有评论,但是他们对此表示赞赏。
你可能想尝试抛出HttpException并在你的javascript中捕获它。
1 | throw new HttpException(401,"Auth Failed") |
在ajax调用,如果会话过期返回这样的东西
1 2 3 | $(function(){ location.reload(); }); |
哈哈...