0
votes

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.

  1. Install CORS.

Cors is installed

  1. Enable CORS in the WebApiConfig class.

Cors Enabled

  1. Enable CORS within the Controller for the given endpoint.

CORS on Controller

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();
1
For .Net 5/ASP.Net Core, try abdulraheem alarpi's suggestion below. For customer headers with CORS in general, look here: developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… - paulsm4

1 Answers

2
votes

just Allow-Headers to access.

In ConfigureServices like that:

services.AddCors(options => options.AddPolicy("name of cors", builder => 
            {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            }));