Wednesday, November 7, 2018

DotNetCor2.1 Api CORS (Enable Cross Origin request)


The cross origin request are sometimes dreadful. This needs to be addressed at the api level

In Dotnet Core 2.1 we can handle it elegantly.


1) Install NuGet package Microsoft.AspNetCore.Cors from NuGet Package Manager.

2) Call AddCors in Startup.ConfigureServices to add CORS services to the app's service container

public void ConfigureServices(IServiceCollection services) { services.AddCors( O => O.AddPolicy("MyPolicy" , builder =>

{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();

}
));


}


3) My project is WebApi so i will use Enable CORS with CORS Middleware

approach.


public void Configure(IApplicationBuilder app, IHostingEnvironment env,

ILoggerFactory loggerFactory)

{ loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Shows UseCors with CorsPolicyBuilder. app.UseCors("MyPolicy");
}

4) Add the attribute [EnableCors("MyPolicy")]

on the controller or on the method if you need to be more specific