Extend IsAjaxRequest() to include fetch api requests

十年热恋 提交于 2020-01-05 08:39:14

问题


I am currently building a site using MVC5 and I need to serve different content when an ajax request is made.

Usually we use jQuery and make an ajax request using $.ajax, but recently we have moved towards using the fetch api. However, requests using the fetch api aren't registering with MVC as ajax requests so the wrong template is being used.

I have thought about making my own is ajax request extension but not sure what header to check for:

    public static bool IsAjaxOrFetchRequest(this HttpRequestBase request)
    {
        if (request != null && request.Headers != null)
        {
            if (request.Headers["Custom-Fetch-Header"] != null)
            {
                return true;
            }
        }

        return request.IsAjaxRequest();
    }

Is there a header that fetch sends with all requests like Request.Headers["X-Requested-With"] == "XMLHttpRequest" ajax sends?

Stepping through the code, I couldn't see anything that stood out


回答1:


Ok looking into this further, I cannot seem to find any standard header being sent with the request so I have created my own header:

const request = new Request(url, {
  headers: new Headers({
    'X-Is-Ajax-Request': 'True'
  })
});

return fetch(request)
  .then(html => {
    const $result = $(html);
    const $content = $result.filter('.js-sidebar-panel-content');
    return $content.length ? $content : $result;
  });

Then I was able to update my extension with:

public static bool IsAjaxOrFetchRequest(this HttpRequestBase request)
{
    if (request != null && request.Headers != null)
    {
        if (request.Headers["X-Is-Ajax-Request"] != null)
        {
            return bool.Parse(request.Headers["X-Is-Ajax-Request"]);
        }
    }

    return request.IsAjaxRequest();
}


来源:https://stackoverflow.com/questions/47353074/extend-isajaxrequest-to-include-fetch-api-requests

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