问题
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