I have a web site 1 and a Web API 2 My Web API have a method name
public string Index()
{
return "Hello world from site 2";
}
In the controller Values. I call from the web site 1 my API like that
$.ajax({
url: relativeUrl,
headers: { "Authorization": "Bearer " + accessToken },
type: "GET"
})
.done(function (result) {
console.log("Result: " + result);
alert(result);
})
.fail(function (result) {
console.log("Error: " + result.statusText);
alert(result.statusText);
});
But I have the following error in my js console.
Access to XMLHttpRequest at ‘Web API 2' from origin ‘Web site 1’ has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
I add in my controller :
[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
In my WebAPIConfig.cs
config.EnableCors();
And in my Web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
But even with that I have still the error, I don't understand what I need to add and where.
You've got
<add name="Access-Control-Allow-Headers" value="Content-Type" />
and
headers: { "Authorization": "Bearer " + accessToken },
In other words, the Access-Control setting only allows the "content-type" header, but your request is sending an "Authorization" header. Clearly these two things don't match up.
The error is very clearly telling you that the "authorization" request header is not being allowed by the Access-Control-Allow-Headers response header.
Try
<add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
instead.
P.S. I don't think you need to use both the web.config settings and the EnableCors action filter at the same time. I think your EnableCors declaration here is redundant. See https://stackoverflow.com/a/29972098/5947043 for more info.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers for more info
I don't know abouth this, But I have faced same problem in Node. I think if you change this
<add name="Access-Control-Allow-Headers" value="Content-Type" />
to
<add name="Access-Control-Allow-Headers" value="*" />
or
<add name="Access-Control-Allow-Headers" value="Authorization" />
since you are calling Authorization header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With