Reputation: 8616
To redirect user to sign in page when session timed out for Ajax request, I implemented following custom attribute,
Code related to Unauthorize request is as follows,
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.Result = new JsonResult
{
Data = new
{
Error = "SessionTimeOut"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();
}
....................
This works fine for ajax requests ($.ajax).
But filterContext.HttpContext.Request.IsAjaxRequest() does not recognize XMLHttp request as an ajax request.
var xhr = new XMLHttpRequest();
xhr.open('POST', "...URL");
xhr.send(formdata);
Does anyone came across similar issue? what would be a solution for this?
Upvotes: 4
Views: 2411
Reputation: 29186
Here's the code for IsAjaxRequest()
in ASP.NET MVC 5
public static bool IsAjaxRequest(this HttpRequestBase request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
return request["X-Requested-With"] == "XMLHttpRequest" || (request.Headers != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
It looks like there is a dependency on a certain header value (X-Requested-With
) being in the request in order for that function to return true.
Here is some more info on X-Requested-With
What's the point of the X-Requested-With header?
You could always look at the jQuery $.ajax()
code itself to see how that is setting the header. To be honest, I wouldn't bother doing ajax without jQuery anyway, it deals with all of these things for you.
Upvotes: 4