Enabling CORS through Web.config vs WebApiConfig and Controller attributes

alex picture alex · Apr 30, 2015 · Viewed 37.8k times · Source

There seems to be two functionally different ways to enable cross-origin request sharing in Web API 2.

One is to import System.Web.Http.Cors, decorate a controller with the EnableCors attribute and to write config.EnableCors() in the WebApiConfig:

[EnableCors(origins: "http://111.111.111.111", headers: "*", methods: "*")]
public class GenericController : ApiController
{
    // etc.

The other is to modify the Web.config:

<system.webServer>
     <httpProtocol>
         <customHeaders>
            <add name="Access-Control-Allow-Origin" value="http://111.111.111.111" />
            <add name="Access-Control-Allow-Methods" value="*" />
            <add name="Access-Control-Allow-Headers" value="*" />

Is there a functional difference between these two different approaches? Which one is correct - don't these accomplish the same thing? If both methods are used to enable CORS, will things blow up?

Answer

Steven V picture Steven V · Apr 30, 2015

If you add the headers to the web.config, every request that is served by that application will include the specified headers. This method is supported at the web server level and doesn't depend on config.EnableCors() being executed. You can use that method to add any HTTP header you want.

On the flip side, the EnableCors attribute requires WebAPI and you need to add some code to make it work. To the end user, the result is the same.

As for which way is better? I've liked keeping those settings in the application code by using the attribute so these settings are obvious to future developers. Depending on your needs, you may want to look into a abstract CorsApiController which your main ApiControllers could inherit to deliver the same CORS headers over and over. But this method won't work if the CORS headers need to vary from controller to controller or from action to action.