Friday, October 10, 2014

Angular.js and ASP.NET MVC: IsAjaxRequest returns false when using $http

In an application we are combining Angular.js on the client and ASP.NET MVC on the server. This all works great until we added a call to Request.IsAjaxRequest inside our MVC controller:

Inside the controller action we check if we have an AJAX request. If this is the case we return a JSON result otherwise we return an HTML view.  We’ve used similar code(in combination with jQuery) in previous projects without any issues. But when calling the MVC action method through Angular’s $http service, we noticed that the Request.IsAjaxRequest() method returned false.

When comparing the requests issued by Angular $http versus jQuery $.get() we noticed one small difference. The xhr call initiated by Angular doesn’t contain the X-Requested-With header. And this is exactly the header ASP.NET MVC is looking for to detect if it’s an AJAX request or not.

We can easily fix this by changing the $httpProvider configuration to include this header with every request:


Anonymous said...

Thanks, worked like a charm!

espy said...

very simple and very effective! Thanks.

Luis Filipe said...

Thank you ... from Brazil (São Paulo)

Mary Brown said...


MVC 5 Training