Missing WebApiConfig.cs in App_Start. Can I use Startup.cs?

I have an ASP.NET Web Api v2 web application and am trying to enable CORS so that I can call the API from a client on another server.

I follow the tutorial located here and it talks about adding the following lines of code to the WebApiConfig.cs file in the App_Start folder ...

 var cors = new EnableCorsAttribute("http://localhost:5901", "*", "*"); config.EnableCors(cors); 

The problem is that I do not have the WebApiConfig.cs directory in the WebApiConfig.cs directory. I do most of my configuration and routing in the Startup.cs file in the root directory of the web application. I don’t remember ever using the WebApiConfig.cs file. Is this code what I can add to Startup.cs ?

+5
source share
1 answer

The answer to your question is simple: Yes, you can.

The only thing that matters is that you apply your settings to the same HttpConfiguration instance, which then goes on to the app.UseWebApi() extension method.

WebApiConfig.cs is the only template file created by the default web API template to separate the web API configuration from other configuration files. If you plan to use only Owin, you can simply ignore it.

[Change] Sample code inside the Startup.cs Configuration method:

 var config = new HttpConfiguration(); var cors = new EnableCorsAttribute("http://localhost:5901", "*", "*"); config.EnableCors(cors); app.UseWebApi(config); 

Responding to comments if you are using app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); , you set the CORS headers at a higher level and then the Web API, and you won’t need to use EnableCorsAttribute at all. The main difference in your case is that with CorsAttribute you will have a fine graded configuration above the CORS header (for example, you can set a different CORS header for each Action method).

Remember to put app.UseCors in front of any other Owin software in your Configuration method.

+4
source

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


All Articles