Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify angular js AJAX calls in ASP.NET MVC code

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?

like image 395
refactor Avatar asked Oct 15 '15 12:10

refactor


People also ask

HOW include AngularJS in ASP.NET MVC?

Form with AngularJS To do that right click on the existing solution, click: File, New, then Project and name it “AngularJSForm“. Now register AngularJS library and others repeating Fig:1.1 – 1.3. In the controller folder let's create HomeController class and generate View. Let's goto Views, Shared, then _layout.

Can we use AngularJS with ASP.NET MVC?

AngularJS can complement the server-side technology, ASP.NET MVC by simplifying and reducing the operations performed by the server. The JavaScript technology supports template engine, dependency injection and routing engine of its own.


1 Answers

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

like image 195
MstfAsan Avatar answered Sep 25 '22 06:09

MstfAsan