Angular中的自定义项不支持Web API
本文关键字:不支持 Web API 自定义 Angular | 更新日期: 2023-09-27 18:17:10
我正在向我的本地Web API服务发送以下请求。
$http.defaults.headers.common.something = 'anything';
$http({
method: 'GET',
url: 'http://localhost/FantasyTradeAnalyzer/api/home/ListLeagues',
})
.success(function (data)
{
$http.defaults.headers.common.something = undefined;
});
和下面的代码在我的Web Api服务
[AcceptVerbs("GET")]
public LeaguesViewModel ListLeagues(HttpRequestMessage request)
{
var re = Request;
var headers = re.Headers;
if (headers.Contains("something"))
{ //do stuff }
}
然而,当我在Fiddler(和c#调试器)中查看时,我没有看到我在Header中发送的自定义字段。我遗漏了什么?这两个东西(Angular和Web Api)都托管在我本地的IIS中,它们是不同的网站。
有趣的是,在URI中添加显式协议(http
)将导致无法添加标题。此外,您应该在配置中使用"headers"选项,这是作为对象传递给$http
的内容。将配置选项传递给配置是多余的,并且不起作用,因为您已经在配置对象中了。
angular.module('app', [])
.controller('TestCtrl', function($http) {
$http({
method: 'GET',
url: 'www.google.com/test',
headers: { 'something': 'anything' }
})
.success(function (data)
{});
});
JSFiddle例子
或者,您可以在$http
上使用简写的.get()
方法。
$http.get(www.google.com/test', {
'something': 'anything' }
)
有几个注意事项值得注意:
如果您正在执行基于自定义报头的任何类型的更新或更改,您应该发送POST或PATCH,因为有一个副作用,并且您不仅仅是只是检索数据。也就是说,有时需要并且应该使用自定义报头发送GET。
这将替换所有的头文件,因此您需要重新添加您需要的任何适用的头文件,因为根据文档,它的功能是重写。
另外,你可以在config对象中提供一个headers属性在调用$http(config)时传递,它会覆盖默认值不需要全局修改
最后,如果你想避免删除默认头,另一个选择是全局修改该头的默认值,尽管你可能想在请求后删除它。这是笨拙和笨拙的,但它消除了您手动重新构建头文件的需要。
angular.module('app', [])
.controller('TestCtrl', function($http) {
$http.defaults.headers.common.something = 'anything';
$http({
method: 'GET',
url: 'www.google.com/test'
})
.success(function (data) {
$http.defaults.headers.common.something = undefined;
});
});
在你的WebAPI方法中检索标题:
var foo = request.Headers.GetValues("test").FirstOrDefault();