使用jQuery发送自定义标头不起作用

时间:2017-10-21 22:35:42

标签: jquery asp.net asp.net-mvc asp.net-web-api

我想将请求标头中的自定义值与Jquery一起发送到我的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中读取请求标头时,它看起来像这样:

连接\ r \ nAccept \ r \ nAccept编码\ r \ nAccept语言\ r \ n主机\ r \ n用户代理\ r \ nAccess控制请求-方法\ r \ nOrigin \ r \ nAccess控制请求报头\ r \ n

我无法使用标题找到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);
}

当我使用小提琴时,网络API会收到自定义密钥。

2 个答案:

答案 0 :(得分:1)

我认为你的问题是,你拦截了选项 - 电话。 如果您没有抛出异常,但是将标题记录到输出或日志文件,则会向您显示,通过第二次调用,真正的Post请求可以很好地添加标题。 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);
    }

}

答案 1 :(得分:0)

你可以试试这个和标题吗?根据您的要求更改值。

$.ajax({
    url: 'https://SOMEAPI.p.mashape.com/', // The URL to the API. You can get this in the API page of the API you intend to consume
    type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
    data: {}, // Additional parameters here
    dataType: 'json',
    success: function(data) { console.dir((data.source)); },
    error: function(err) { alert(err); },
    beforeSend: function(xhr) {
    xhr.setRequestHeader("X-Mashape-Authorization", "YOUR-MASHAPE-KEY"); // Enter here your Mashape key
    }
});