Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling CORS through Web.config vs WebApiConfig and Controller attributes

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?

like image 532
alex Avatar asked Apr 30 '15 14:04

alex


People also ask

How do I enable CORS on Webapiconfig?

You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method. The following example enables CORS for the GetItem method only.

What is enable CORS in Web API?

Cross-origin resource sharing (CORS) is a browser security feature that restricts cross-origin HTTP requests that are initiated from scripts running in the browser. If your REST API's resources receive non-simple cross-origin HTTP requests, you need to enable CORS support.


1 Answers

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.

like image 179
Steven V Avatar answered Nov 11 '22 11:11

Steven V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!