I am making an ajax call using jquery for an asp.net mvc controller action:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult GetWeek(string startDay) { var daysOfWeek = CompanyUtility.GetWeek(User.Company.Id, startDay); return Json(daysOfWeek); }
When the session time ends, this call will not be completed because the user object will be saved in the session. I created a special authorization attribute to check if the session was lost and redirected to the login page. This works fine for page requests, however it does not work for ajax requests, since you cannot redirect an ajax request:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorizeUserAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!httpContext.Request.IsAjaxRequest()) {
I read in another thread that when the user is not authenticated and you make an ajax request, you must set the status code to 401 (unauthorized) and then check it in js and redirect to the login page. However, I cannot get this to work:
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (Request.IsAjaxRequest() && (!Request.IsAuthenticated || User == null)) { filterContext.RequestContext.HttpContext.Response.StatusCode = 401; } else { base.OnActionExecuting(filterContext); } }
Basically, he will set it to 401, but then he will continue the action of the controller and throw away the ref object not set in the object error instance, which then returns the 500 error back to the client side js, If I change my own Authorize attribute to check ajax- requests, and also return false for those that did not authenticate, this makes the ajax request return my login page, which obviously does not work.
How do I make this work?
jquery asp.net-mvc asp.net-mvc-3
Justin Mar 08 2018-11-11T00: 00Z
source share