Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an ASP.NET Web Api v2 web app and I am trying to enable CORS so I can call the API's from a client on a different server.

I am following a 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 I don't have a WebApiConfig.cs in the App_Start directory. I do most of my configuration and routing in the Startup.cs file in the root of the web application. I don't recall ever using a WebApiConfig.cs file. Is this code something I can add to Startup.cs?

like image 268
webworm Avatar asked Apr 13 '16 18:04

webworm


1 Answers

The answer of your question is simply: Yes, you can.

The only thing that matters is that you apply your settings to the same HttpConfiguration instance you will then pass to app.UseWebApi() extension method.

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

[Edit] Sample code, inside your 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 use app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); then you are setting CORS headers at a higher level then Web API, and you will not need to use EnableCorsAttribute at all. The main difference in your case is that with CorsAttribute you'll have a fine graded configuration over the CORS header (e.g. you could set a different CORS header for every Action method).

Just remember to put app.UseCors before any other Owin middle-ware in your Configuration method.

like image 106
Federico Dipuma Avatar answered Nov 15 '22 09:11

Federico Dipuma