Enabling CORS through Web.config vs WebApiConfig and Controller attributes

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

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

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

Another is to modify 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 difference between these two different approaches? Which one is right - isn't that the same? If both methods are used to enable CORS, will everything explode?

+6
source share
1 answer

If you add headers to the web.config file, the request each served by this application will contain the specified headers. This method is supported at the web server level and is independent of the executable config.EnableCors() . You can use this method to add any HTTP header you want.

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

Which is better? I liked to save these parameters in the application code using the attribute, so that these parameters were obvious to future developers. Depending on your needs, you might want to take a look at the abstract CorsApiController that your main ApiControllers could inherit in order to play the same CORS headers over and over again. But this method will not work if the CORS headers must change from controller to controller or from action to action.

+3
source

Source: https://habr.com/ru/post/986307/


All Articles