Posts from ‘WebAPI’

Aug
26

In a development environment it may be handy to enable CORS for testing. Sometimes you need to expose custom headers as well. So let’s get our Access-Control-Expose-Headers’ing on.

With the out of the box WebAPI 2 setting up CORS with a custom header is easy. After we have added Microsoft.AspNet.WebApi.Cors to our project we just have to add the following to our WebApiConfig:

config.EnableCors(new EnableCorsAttribute("*", "*", "*", "X-Custom-Header"));

However, if you are using the Owin middleware version (Microsoft.Owin.Cors) you will have to setup a custom CorsOptions object. Currently your Cors middleware config may look like this:

app.UseCors(CorsOptions.AllowAll); // Note: Make sure to call app.UseCors() before you load in any additional middleware that will use requests. (Like app.UseWebApi(config);)

Lets take a look at what CorOptions.AllowAll does:
Microsoft.Owin.Cors CorsOptions.AllowAll Option
We can see that all it is doing is creating a custom CorsOption object for us with some default settings. The meat of the configuration is located in the CorsPolicy object. You’ll notice one particular property of CorsPolicy that is of particular interest of us: CorsPolicy.ExposedHeaders This read-only list contains a collection of headers to expose via Cors.

To bring it all together, we will need to recreate the object CorsOptions.AllowAll made for us, as well as appending some custom headers to our new CorsPolicy:
Cors Setup with custom CorsOptions and CorsPolicy options.