I want to allow access to all the origins with basic authentication enabled in Web API but whenever I try to call the API through ajax it gives an error stating
No 'Access-Control-Allow-Origin' header is present on the requested resource. (CORS issue)
I tried the below mentioned snippet(in webapiconfig). It worked fine in localhost but after hosting it in IIS it's giving the same error again.
var corsAttr = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true };
config.EnableCors(corsAttr);
I have implemented basic authentication from below link :
https://www.c-sharpcorner.com/blogs/basic-authentication-in-webapi
Also tried commenting the aforementioned snippet and adding the below lines in Web.config but this too failed
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Authorization, Content-Type"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE"/>
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
AJAX call :
function post()
{
var data = {xyz};
$.ajax({
url : 'http://localhost:8080/api/demo',
type: 'POST',
dataType: 'json',
data: data,
headers: { 'Authorization': 'Basic ' + btoa('abc' + ":" + 'xyz') },
success: function (response) {
alert('Success');
},
error: function (response) { alert('Error'); }
});
}
I expect that my API should be accessed with credentials irrespective of Origin.
Use the below command to disable same origin policy in Chrome.
1.Close Chrome.
2.Open Run.
3.Type chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
and try invoking the API.
Sometimes other errors results in CORS
error. In my case I was struggling with CORS
error and I already tried everything.
When I tried to monitor incoming requests on server with wireshark tools I realized that my requests don't hit server at all.
In fact, although CORS
error made me think error is due to configs on application but it was a firewall issue and whole service was inaccessible. After doing proper configs on firewall CORS
error gone too
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.