Identify angular js AJAX calls in ASP.NET MVC code

2020-07-03 04:34发布

问题:

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?

回答1:

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