2

This is not quite a duplicate; the answer provided below is identical to a comment in the proposed duplicate answer.

From inside an asp.net controller action, I'm interested in knowing if the call was made by a javascript fetch() call. Is there any part of the Request object that I can interrogate to discover this?

For example, if I'm interested in knowing if the caller is a javascript $.ajax call, on the server-side I can call this method:

Request.IsAjaxRequest();

and if it returns true I know that the call was something like this:

       $.ajax({
        url: '/MyDomain/MyControllerAction',
        type: 'GET',
        success: function (data) {
            doSomething(data);
        },
        error: function (XMLHttpRequest, ajaxOptions, ex) {
            doSomethingElse(XMLHttpRequest, ajaxOptions, ex);
    });

Is there something like Request.IsAjaxRequest() I can call or interrogate to discover if the caller was a javascript fetch(), eg a call like this:

fetch('/MyDomain/MyControllerAction')
       .then(function (data) {
          if(data.ok){
            return data.json();
           }
        })
        .then(function (data) {
            doSomething(data)
        })
        .catch(function (error) {
            doSomethingElseAgain(error);
        });
Tom Regan
  • 3,580
  • 4
  • 42
  • 71
  • Do you want to treat `fetch` differently from `$.ajax`? Or do you want them to behave the same on the server? – p.s.w.g Mar 07 '19 at 19:25
  • I would expect `IsAjaxRequest` to have the same behavior, is that not the case? Or are you trying to differentiate between `$.ajax()` and `fetch()` as well? Why do you need to know this anyway? – David Mar 07 '19 at 19:26
  • IsAjaxRequest() does not return true for a fetch() request, that is why I posted the question. As far as "why", I need to know so that I know how to handle errors. I originally asked the question this way, but I realized I was including far too much information: https://stackoverflow.com/questions/55048830/how-recognize-javascript-fetch-inside-handleerrorattribute-onexception – Tom Regan Mar 07 '19 at 19:26
  • You mean like `app.get('/MyDomain/MyControllerAction', function(req, res) {` ? – Roko C. Buljan Mar 07 '19 at 19:27
  • Possible duplicate of [Extend IsAjaxRequest() to include fetch api requests](https://stackoverflow.com/questions/47353074/extend-isajaxrequest-to-include-fetch-api-requests) – dom Mar 07 '19 at 19:33

1 Answers1

6

From this answer, IsAjaxRequest checks a specific HTTP header that's set by $.ajax. To make IsAjaxRequest return true for fetchset this header when you make your request, like this:

fetch('/MyDomain/MyControllerAction', { headers: { 'X-Requested-With': 'XMLHttpRequest' } })

See MDN for a full list of fetch options.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331