13

I am working on a sample application using ASP.NET MVC and AngularJS.

In server side code , I have written a Action filter attribute , and in that I need to check whether the request is a normal request(Browser) or AJAX request.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if ( filterContext.HttpContext.Request.IsAjaxRequest())
     {

     }
}

The method mentioned in the above code snippet "IsAjaxRequest()" is not returning TRUE in case of AJAX request made using $http Angular service.

I observed that the request does not have X-Requested-With header , and even adding the header did not solve the request.

Note : This is NOT CORS call.

So My question.

  1. How does filterContext.HttpContext.Request.IsAjaxRequest() decide whether the request is AJAX or not?

  2. I can check the request header(whether it has a particular header or not) and decide whether the request is AJAX or not. Is it the right and only approach?

refactor
  • 13,954
  • 24
  • 68
  • 103
  • 1
    Just an fyi that it's open source and you can look at the actual implementation: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/AjaxRequestExtensions.cs – Keith Rousseau Oct 15 '15 at 13:08
  • @Keith Rousseau Link provided should be helpful for me in the future.. – refactor Oct 15 '15 at 15:21

1 Answers1

20

It decides by looking whether X-Requested-With header exists or not. You can add X-Request-With header manually to $http service.

Individual request

$http.get('/controller/action', {
   headers: {
    'X-Requested-With': 'XMLHttpRequest'
   }
});

For every request

app.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

You can see why it is missing from Angular

Mustafa ASAN
  • 3,747
  • 2
  • 23
  • 34
  • In fact I did add the header suggested , but the issue was with the value of header , instead of "XMLHttpRequest" it was "true" , God knows why I gave that value :). Link provided is also helpful. Thanks. – refactor Oct 15 '15 at 15:14