From server, how recognize javascript fetch() call was made (asp.net mvc)

隐身守侯 提交于 2019-12-11 19:17:10

问题


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);
        });

回答1:


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.



来源:https://stackoverflow.com/questions/55051359/from-server-how-recognize-javascript-fetch-call-was-made-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!