I have a problem with Ajax requests and redirects. I tried creating a custom authorize attribute as follows:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result == null || (filterContext.Result.GetType() != typeof(HttpUnauthorizedResult)
|| !filterContext.HttpContext.Request.IsAjaxRequest()))
return;
var redirectToUrl = "/login?returnUrl=" + filterContext.HttpContext.Request.UrlReferrer.PathAndQuery;
filterContext.Result = (filterContext.HttpContext.Request.ContentType == "application/json"
? (ActionResult)
new JsonResult
{
Data = new { RedirectTo = redirectToUrl },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
}
: new ContentResult
{
Content = redirectToUrl,
ContentEncoding = System.Text.Encoding.UTF8,
ContentType = "text/html"
});
//Important: Cannot set 401 as asp.net intercepts and returns login page
//so instead set 530 User access denied
filterContext.HttpContext.Response.StatusCode = 530; //User Access Denied
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
But the isAjaxRequest() is always false in my application. Even when I am calling the action from a jquery .ajax() call.
EDIT: Including the ajax calls as suggested. Some of my ajax calls are made by the jqGrid component. The datatype is set to JSON and type is POST. The controllers have the HTTPPost decoration. Some of them are direct jquery ajax calls like so:
$("#clientList").change(function () {
var client = $("#clientList").val();
$.ajax({
url: "myurl",
data: { 'client': client },
cache: false,
traditional: true,
type: 'POST',
success: function (data) {
<do something here>
}
});
});