识别ASP.NET MVC代码中的Angular js AJAX调用 [英] Identify angular js AJAX calls in ASP.NET MVC code
问题描述
我正在使用ASP.NET MVC和AngularJS开发示例应用程序.
I am working on a sample application using ASP.NET MVC and AngularJS.
在服务器端代码中,我编写了一个动作过滤器属性,并需要检查该请求是普通请求(浏览器)还是AJAX请求.
In server side code , I have written a Action filter attribute , and in that I need to check whether the request is a normal request(Browser) or AJAX request.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if ( filterContext.HttpContext.Request.IsAjaxRequest())
{
}
}
在使用$ http Angular服务发出AJAX请求的情况下,上述代码段"IsAjaxRequest()"中提到的方法未返回TRUE.
The method mentioned in the above code snippet "IsAjaxRequest()" is not returning TRUE in case of AJAX request made using $http Angular service.
我发现请求没有X-Requested-With标头,甚至添加标头也无法解决请求.
I observed that the request does not have X-Requested-With header , and even adding the header did not solve the request.
注意:这不是CORS呼叫.
Note : This is NOT CORS call.
所以我的问题.
-
filterContext.HttpContext.Request.IsAjaxRequest()如何确定请求是否为AJAX?
How does filterContext.HttpContext.Request.IsAjaxRequest() decide whether the request is AJAX or not?
我可以检查请求标头(是否具有特定标头),并确定请求是否为AJAX.这是正确且唯一的方法吗?
I can check the request header(whether it has a particular header or not) and decide whether the request is AJAX or not. Is it the right and only approach?
推荐答案
它通过查看X-Requested-With
标头是否存在来进行确定.
您可以将X-Request-With
标头手动添加到$http
服务.
It decides by looking whether X-Requested-With
header exists or not.
You can add X-Request-With
header manually to $http
service.
个人要求
$http.get('/controller/action', {
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
对于每个请求
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
这篇关于识别ASP.NET MVC代码中的Angular js AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!