Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - What does IsAjaxRequest() actually mean?

I had previously created a method on my base controller:

public bool IsJsonRequest()
{
    var acceptTypes = Request.AcceptTypes;
    return acceptTypes != null && 
           acceptTypes.Any(a => a.Equals("application/json",
                                         StringComparison.OrdinalIgnoreCase));
}

Then I stumbled upon AjaxRequestExtensions.IsAjaxRequest(). The documentation for it is very vague:

true if the specified HTTP request is an AJAX request; otherwise, false.

This got me thinking, what does it about an HTTP request that makes it AJAX? Is there more to it than checking the requester's accepted content types, or is encoding not a requirement of being 'AJAX'?

(Note that in my case my actions should only be called from JS pages on my site, and JSON is the only necessary encoding.)

like image 457
Drew Noakes Avatar asked Dec 24 '10 02:12

Drew Noakes


2 Answers

It checks for the X-Requested-With (HTTP_X_REQUESTED_WITH) header being set to XMLHttpRequest. This header is set by jQuery and a number of other javascript frameworks when making AJAX requests.

like image 163
tvanfosson Avatar answered Sep 28 '22 04:09

tvanfosson


Specifically, the IsAjaxRequest code can be broken down to the function:

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

Edit - 21st January 2019

I went back to my answer and found that my link to IsAjaxRequest is now broken. I've updated it with the current link but this is the AspNetWebStack repo and as such, is not the MVC v3 version of the code. That said, at time of looking, the code is still identical to what I wrote above.

like image 32
Dan Atkinson Avatar answered Sep 28 '22 04:09

Dan Atkinson