XMLHttpRequest () not recognized as IsAjaxRequest?

To redirect the user to the login page when the session timed out for an Ajax request, I executed the following user attribute.

The code associated with the 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 great for ajax requests ($ .ajax).

But filterContext.HttpContext.Request.IsAjaxRequest () does not recognize the XMLHttp request as an ajax request.

var xhr = new XMLHttpRequest();
                xhr.open('POST', "...URL");
                xhr.send(formdata);

Has anyone encountered a similar problem? what would be the solution for this?

+3
source share
1 answer

Here is 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");
}

, (X-Requested-With), true.

X-Requested-With

X-Requested-With?

jQuery $.ajax(), , . , ajax jQuery , .

+2

All Articles