扩展IsAjaxRequest()以包括获取api请求 [英] Extend IsAjaxRequest() to include fetch api requests
问题描述
我目前正在使用MVC5构建站点,并且在发出Ajax请求时需要提供不同的内容.
I am currently building a site using MVC5 and I need to serve different content when an ajax request is made.
通常,我们使用jQuery并使用$.ajax
发出ajax请求,但是最近我们已经转向使用fetch api.但是,使用fetch api的请求不会像ajax请求一样在MVC中注册,因此使用了错误的模板.
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.
我曾经考虑过自己制作一个ajax请求扩展,但是不确定要检查哪个标头:
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();
}
是否存在与所有请求(例如Request.Headers["X-Requested-With"] == "XMLHttpRequest"
ajax发送)一起发送的标头?
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
推荐答案
还可以进一步研究,我似乎找不到与请求一起发送的任何标准标头,因此我创建了自己的标头:
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();
}
这篇关于扩展IsAjaxRequest()以包括获取api请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!