且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jquery无法发送自定义标头

更新时间:2022-04-14 07:29:14

.ajax({

类型:发布,

crossDomain:true ,

url:'http:// localhost:61190 / webapi',

dataType:'json',

cache:false,

标题:{

'mykey':'value',

'Content-Type':'application / json'

}

});

< / script>



我的网络API



protected void Application_PostAuthorizeRequest()

{

string keys =;

for(int i = 0; i< HttpContext.Current.Request.Headers.Count; i ++)

{

keys + = HttpContext.Current.Request.Headers.Keys [i] .ToString()+ Environment.NewLine;

}

抛出新的异常(键);

}
.ajax({
type: "Post",
crossDomain: true,
url: 'http://localhost:61190/webapi',
dataType: 'json',
cache: false,
headers: {
'mykey':'value',
'Content-Type':'application/json'
}
});
</script>

My web API

protected void Application_PostAuthorizeRequest()
{
string keys = "";
for (int i = 0; i < HttpContext.Current.Request.Headers.Count; i++)
{
keys += HttpContext.Current.Request.Headers.Keys[i].ToString() + Environment.NewLine;
}
throw new Exception(keys);
}


跨域AJAX请求更加复杂:

AJAX跨域|跨源请求| jQuery CORS [ ^ ]



XHR组件最初会向服务器发出飞行前请求,没有任何数据或自定义标头,以确保服务器上的CORS设置允许请求。



您的服务器无条件地为每个请求抛出异常,因此飞行前请求失败,并且永远不会发送真实请求。



尝试更改代码以检查 HttpContent.Current.Request.HttpMethod 在查找自定义标头之前设置为POST 。



您还需要确保在响应中发送正确的CORS标头。

在ASP.NET Web API中启用跨源请求2 | Microsoft Docs [ ^ ]
Cross-domain AJAX requests are more complicated that that:
AJAX Cross Domain | Cross-Origin Request | jQuery CORS[^]

The XHR component will initially make a "pre-flight" request to the server, without any data or custom headers, to ensure that the CORS settings on the server will allow the request.

Your server is unconditionally throwing an exception for every request, so the pre-flight request fails, and the real request is never sent.

Try changing your code to check that HttpContent.Current.Request.HttpMethod is set to "POST" before looking for your custom header.

You'll also need to make sure you're sending the correct CORS headers in the response.
Enabling Cross-Origin Requests in ASP.NET Web API 2 | Microsoft Docs[^]