Generic_Dev_24
Generic_Dev_24

Reputation: 21

How do I enable custom headers with CORS?

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();

Upvotes: 2

Views: 2028

Answers (3)

Abdus Salam Azad
Abdus Salam Azad

Reputation: 5502

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: "*")]

Upvotes: 0

abdulraheem alarpi
abdulraheem alarpi

Reputation: 177

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();
            }));

Upvotes: 2

abdulraheem alarpi
abdulraheem alarpi

Reputation: 177

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

https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Upvotes: 0

Related Questions