13

is there a way to tell if a request is an Angular (1.1.5) $resource request. I'm pretty much looking for a "Request.IsAjaxRequest()" method for this type of request.

I'm looking this as in the HandleUnauthorizedRequest of an overriden AuthorizeAttribute I need to set the context result to some json if an Ajax or angular request or something else if not.

4
  • Why don't use a simple system token ? Or you just want make the difference between ajax request and classic mvc request ? Commented Sep 25, 2013 at 9:45
  • 1
    Just looking to know the difference so that I can either send back json or redirect to another mvc view. Commented Sep 25, 2013 at 10:27
  • Does the MVC method Request.IsAjaxRequest not help? Commented Sep 25, 2013 at 10:56
  • Nope, as the that checks for the 'X-Requested-With' header which was not present (see Thomas' updated answer) Commented Sep 25, 2013 at 15:19

1 Answer 1

36

I don't know well MVC3 but you can set a custom header for all request from AngularJS.

Then on server side you just have to get this header and do what you want with request from angular.

To have custom header in AngularJS just do this :

angular.module('myModule', [])

    .config(['$httpProvider', function($httpProvider) {

        $httpProvider.defaults.headers.common["FROM-ANGULAR"] = "true";

    }])

For use the X-Requested-With you have to do this too :

$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

It's not set by default anymore because a lot part of the community have to delete this header to enable CORS request

Sign up to request clarification or add additional context in comments.

4 Comments

Cheers, this works well, though I was initially hoping there was a header already in there I could check. Do you know why it does not get sent with X-Requested-With?
By default now no before yes. github.com/angular/angular.js/commit/…
This is particularly useful if you are using Yii as your backend and you rely on the isAjaxRequest property.
Also useful for general PHP framework isAjax logic. Phalcon has a similar function too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.