Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is correct order to AddCors into .Net Core?

First MVC middleware or Cors Middleware.

    services.AddMvc()
    services.AddCors();

Sorry official doc mentions above however I have seen other examples with reverse order working fine as well.

Could you share a glimple on internals on how it works?

like image 473
Abhijeet Avatar asked Apr 16 '19 10:04

Abhijeet


People also ask

Does the order of ConfigureServices matter?

Adding services to the service collection is not order dependent by default (Does not include 3rd Party integration frameworks that interact with the service collection).

How do I add a CORS header in .NET core?

Set the allowed request headersAddCors(options => { options. AddPolicy(name: MyAllowSpecificOrigins, policy => { policy. WithOrigins("https://*.example.com") . AllowAnyHeader(); }); }); builder.

What is CORS policy in .NET core?

CORS means cross-origin resource sharing. You'll see more in just a minute, but in a nutshell, CORS is a mechanism—an HTTP protocol, to be exact—that allows web applications to access resources hosted on different domains (or origins.)


2 Answers

Services using AddX()

When registering services inside ConfigureServices, the order in which you call the AddX() methods usually does not matter. So you can order and logically group them in the way that makes most sense to you.

The only way the order would actually matter if there are multiple service registrations of the same type, in which case the latest registration would win. The default framework parts are usually not built in such a way though. Instead, they are actually built in a way that they can be called multiple times without a problem. This is especially useful when you want to reconfigure certain services later.

For AddMvc() and AddCors(), both methods will register a separate set of services, so there is really no difference when calling one earlier than the other.

Note that neither AddMvc() nor AddCors() do actually set up any middleware. They just prepare the necessary services that the middlewares need in order to run. The middleware is configured inside of the Configure method.

Middleware using app.UseX()

The middleware is configured in Configure and there the order in which you register each middleware does matter.

The middleware is a chained pipeline that runs in the order you register it:

Middleware pipeline

In order to have one middleware affect another middleware, it will need to execute around that other middleware. So in your case, since you want to enable CORS for the MVC middleware, so that you can properly request routes within MVC from other origins, you will need to register the CORS middleware before the MVC middleware.

You can also take a look at the implementation of the CORS middleware. As you can see the call to next() is at the very end of it, so that means that the relevant logic of the CORS middleware runs before it executes the next middleware. That’s a good sign that it needs to run first.

So the correct order is:

app.UseCors();
app.UseMvc();

As a general rule, the MVC middleware almost always should come last.

like image 96
poke Avatar answered Sep 30 '22 15:09

poke


No, it's other way round. You should first add the CORS middle-ware before adding MVC middle-ware like below. Example taken from Enable Cross-Origin Requests (CORS) in ASP.NET Core

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("http://example.com",
                                "http://www.contoso.com");
        });
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
} 

So does while using it

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(MyAllowSpecificOrigins); 
    app.UseMvc();
}

If you read through the linked documentation it clearly says that

Note:

UseCors must be called before UseMvc.

like image 28
Rahul Avatar answered Sep 30 '22 13:09

Rahul