Pages

Wednesday, October 11, 2017

In this post let’s see how we can apply CORS policies for different scenarios (based on the route/path etc.) in an ASP.NET Core 2.0 Web Application.

As you already know, in ASP.NET Core projects, on the Startup.cs, we have 2 methods ConfigureServices and Configure, and these two will get called by the runtime. ConfigureServices is used to add services to the container, so we can use them through out the application. Configure method is used to configure the HTTP Request pipeline.

So moving to the topic, first thing we need to do is AddCors to IoC container, (again so we can consume this through out the application). (Note: these is an alternate way, and I will be describing that later in the post, keep reading forward)

Note: The precedence order is: Action, controller, global. Action-level policies take precedence over controller-level policies, and controller-level policies take precedence over global policies.

Custom

Imagine, you want to apply CORS policy based on HTTP Request route/path etc. You can use the power of Middleware for that kind of a scenario.

One approach would would be, you can use app.Map and app.MapWhen to branch off the HTTP Request pipeline and use app.UseCors as shown in above, but the downside is your HTTP Request pipeline is getting short-circuited. That of course you can merge back, but personally I don’t find it a good approach.

The other approach (which I personally find best) is, you can easily create a separate Middleware class for handling CORS in following way.

The whole piece of code is taken from CorsMiddleware.cs (cheers to Microsoft for going open source), and we can just modify it to match our need. Here I have modified it to apply CORS policy based on the request route/path. Now you can simply do following.

Tuesday, October 10, 2017

As you might know and as of today, for Entity Framework Core, Microsoft does not support Automatic Database Migrations as in Entity Framework Full. The reasons are described in this Issue. But it doesn't stop you from configuring automatic migrations by your own. You can just write something like below and call this inside Startup -> Configure method passing the IApplicationBuilder.