Click here to Skip to main content
15,917,971 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to send a custom value in the request header with Jquery to my Web API. 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

I cannot find mykey value with the header when call the web API from Google Chrome. When I use fiddle to call the web API, I receive the custom key. . I read the header in the the Gobal.aspx

What I have tried:

<script>
$.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);
}
Posted
Updated 24-Oct-17 7:59am

1 solution

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[^]
 
Share this answer
 
Comments
elshorbagy 27-Oct-17 8:15am    
But when I use fiddle the web API can get the custom header correctly.
Richard Deeming 27-Oct-17 8:21am    
Because Fiddler is a desktop application, and is not subject to the same CORS restrictions as a web page.
elshorbagy 29-Oct-17 18:14pm    
I disabled the throw exception method and I added these lines to my webconefig but nothing has changes
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With,x-my-custom-header,jtv, Content-Type, Accept, Authorization" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900