I am attempting to set up CORS on my C# Web API following Microsoft's guide which can be found here. Here are the steps I followed.
- Install CORS.
- Enable CORS in the WebApiConfig class.
- Enable CORS within the Controller for the given endpoint.
Now it should be noted that this endpoint does require a custom header. My current understanding is that when I use the EnableCors attribute and use a wildcard "*" for the headers, then all headers are allowed. However, when I attempt to call this endpoint I'm met with the following error in Chrome dev tools.
Access to XMLHttpRequest at 'https://myapi/getdata/myid' from origin 'http://localhost:12345' has been blocked by CORS policy: Request header field myheaderfield is not allowed by Access-Control-Allow-Headers in preflight response.
I've tried changing the allowed headers from wildcard "*" to "myheaderfield" but the error remains the same. How do I enable custom headers with CORS?
Below is the JS XHR request I am using to make this call.
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://myapi/getdata/myid");
xhr.setRequestHeader("myheaderfield", "abc123");
xhr.send();
CodePudding user response:
just Allow-Headers to access In asp.net core
In ConfigureServices like that:
services.AddCors(options => options.AddPolicy("name of cors", builder =>
{
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
}));
CodePudding user response:
In Asp.Net 4.7.2 To allow any headers, set headers to "*". To allow specific headers, set headers to a comma-separated list of the allowed headers Like That:
[EnableCors(origins: "http://example.com",
headers: "accept,content-type,origin,x-my-header", methods: "*")]
And This Link Explaine Full Cors In .Net FrameWork
CodePudding user response:
In .NET 4.7, if you want to add custom header globally, then do like the following on your Register method:
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
// ...
}
If you want as per controller, then add config.EnableCors(cors);
on your Register method and on your controller do like below:
[EnableCors(origins: "http://example.com",
headers: "accept,content-type,origin,x-my-header", methods: "*")]