我想使用 Jquery 将请求 header 中的自定义值发送到我的 Web API。这是我的脚本:
<script>
$.ajax({
type: "Post",
crossDomain: true,
url: 'http://localhost:61190/webapi',
dataType: 'json',
cache: false,
headers: {
'mykey':'value',
'Content-Type':'application/json'
}
});
</script>
当我在 Web API 中读取请求 header 时,它看起来像这样:
连接\r\n接受\r\n接受编码\r\n接受语言\r\n主机\r\n用户代理\r\n访问控制请求方法\r\n来源\r\n访问控制请求 header \r\n
并且我无法通过 header 找到 mykey 值。我读了 Gobal,aspx 中的标题
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);
}
当我使用 fiddle 时,Web API 接收自定义 key 。
最佳答案
我认为你的问题是,你拦截了选项调用。 如果您没有抛出异常,而是将 header 记录到输出或日志文件中,则会向您显示,通过第二次调用,真正的 Post 请求 header 已添加完毕。 options-request 是因为跨域调用。
更新3: 我会尝试什么:仅过滤 POST
protected void Application_PostAuthorizeRequest()
{
if(HttpContext.Current.Request.HttpMethod.Equals("POST")==true)
{
string keys = "The count of headers is: " + HttpContext.Current.Request.Headers.Count.ToString() + " values: " + Environment.NewLine;
for (int i = 0; i < HttpContext.Current.Request.Headers.Count; i++)
{
keys += HttpContext.Current.Request.Headers.Keys[i].ToString() + Environment.NewLine;
}
// don't throw this Exception, if the request is of Type Options.
throw new Exception(keys);
}
}
关于jquery - 发送自定义 header ,jQuery 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46868772/