Daina Hodges
Daina Hodges

Reputation: 853

Send custom header with jQuery not working

I want to send a custom value in the request header with Jquery to my Web API. This is my script:

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

When I read the request header in the web API, it looks like this:

Connection\r\nAccept\r\nAccept-Encoding\r\nAccept-Language\r\nHost\r\nUser-Agent\r\nAccess-Control-Request-Method\r\nOrigin\r\nAccess-Control-Request-Headers\r\n

And I cannot find mykey value with the header. I read the header in the the 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);
}

When I use fiddle the web API receive the custom key.

Upvotes: 1

Views: 419

Answers (2)

Nikolaus
Nikolaus

Reputation: 1869

I think your problem is, that you intercept the options-call. If you didn't throw an Exception, but log the headers to a Output or a logfile, would show you, that with the second call, the real Post request the headers are well added. The options-request is because of the cross-origin call.

Update 3: What I would try: Filter only 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);
    }

}

Upvotes: 2

DesignerAshish
DesignerAshish

Reputation: 81

Can you please try this one for headers & change values as per your requirement.

$.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
    }
});

Upvotes: 0

Related Questions