4

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?

Dhanuka777
  • 7,389
  • 5
  • 61
  • 112

1 Answers1

4

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.

Community
  • 1
  • 1
Jason Evans
  • 28,042
  • 13
  • 88
  • 145
  • 1
    Yes you are correct, in my case, in a WebWorker I have to use XMLHttpRequest instead $.ajax, then I'm using that header: `var _XMLHttpRequest = new XMLHttpRequest(); `_XMLHttpRequest.open("POST", ..., true); ` _XMLHttpRequest.setRequestHeader("__RequestVerificationToken", ...); ` _XMLHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest"); ` _XMLHttpRequest.responseType = 'json'; ` _XMLHttpRequest.send(...); – pas Apr 06 '20 at 10:05