ASP.NET’s IsAjaxRequest Doesn’t Work with AngularJS

1 Comment

In ASP.NET, it can be helpful to know when a request is an AJAX call (made via XMLHttpRequest, that is) as apposed to a standard HTTP request. This can be detected with ASP.NET’s Request.IsAjaxRequest() method. This helper method returns true whenever the HTTP request contains the header “X-Requested-With” with a value of “XMLHttpRequest“.

JQuery handles this automatically for you with any calls made using its $.ajax() method. AngularJS, however, does not. When you’re creating and AngularJS application, this can make it difficult to detect when a request to the server was an AJAX request or not.

Have no fear, though, you can fix this problem with one simple line of code in our AngularJS application:

When you configure your application module, add $httpProvider as a dependency and use it set a the “X-Requested-With” header’s default value to “XMLHttpRequest”. Now all requests made with $http in your Angular app will automatically send this header for each request, allowing ASP.NET to detect it as an AJAX request.