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:
public class ProductController:Controller | |
{ | |
public ActionResult All() | |
{ | |
var products=ProductRepository.GetAll(); | |
if(Request.IsAjaxRequest()) | |
{ | |
return Json(products,JsonRequestBehavior.AllowGet); | |
} | |
else | |
{ | |
return View(products); | |
} | |
} | |
} |
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:
var productsApp = angular.module('productsApp', []); | |
productsApp.config(['$httpProvider', function ($httpProvider) { | |
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; | |
}]); | |