In this post, we will focus on how to enable CORS in ASP.Net Core application, get knowledge about CORS policy, and how we can share resources through different origins.
The following topics will be discussed.
- What is CORS?
- Create .NET Core WebAPI Application
- Add Packages
- Add Database Connection
- Enable CORS
- Publishing to IIS
- Share Through .NET Core Sample Application
Introduction
First, let’s get introduced to CORS. According to Wikipedia, "Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the resource originated."
Get more details from docs.asp.net. Let’s get started with a sample application.
Create New Application
Open Visual Studio 2015, then go top menu. and Click > File > New > Project

Choose Web API template.

Finally, .Net Core Welcome page will appear. Read more about .NET Core.

First, we need to add required packages to the sample application. Here, we have added those packages listed below in project.json file. After putting all those packages in our project config file, they will automatically be added to our application by IDE.
project.json
- //EntityFrameworkCore
- "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
- "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
- "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1",
- "Microsoft.EntityFrameworkCore": "1.0.1",
- //Cross Origin Resource Sharing
- "Microsoft.AspNetCore.Cors": "1.0.0"
appsettings.json
- {
- "ConnectionStrings": {
- "dbConn": "Server=DESKTOP-JAKRV2S;Database=PhoneBook;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Debug",
- "System": "Information",
- "Microsoft": "Information"
- }
- }
- }
- publicvoidConfigureServices(IServiceCollection services) {
- //Add database services.
- varconnectionString = this.Configuration.GetConnectionString("dbConn");
- services.AddDbContext < PhoneBookContext > (options => options.UseSqlServer(connectionString));
- // Add framework services.
- services.AddApplicationInsightsTelemetry(Configuration);
- services.AddMvc();
- }
Here, we have also specified different CORS enabled policies by using CorsPolicyBuilder. You may test by enabling different types with this sample application.
Startup.cs ConfigureServices
- services.AddCors(
- options => options.AddPolicy("AllowCors",
- builder => {
- builder
- //.WithOrigins("http://localhost:4456") //AllowSpecificOrigins;
- //.WithOrigins("http://localhost:4456", "http://localhost:4457") //AllowMultipleOrigins;
- .AllowAnyOrigin() //AllowAllOrigins;
- //.WithMethods("GET") //AllowSpecificMethods;
- //.WithMethods("GET", "PUT") //AllowSpecificMethods;
- //.WithMethods("GET", "PUT", "POST") //AllowSpecificMethods;
- .WithMethods("GET", "PUT", "POST", "DELETE") //AllowSpecificMethods;
- //.AllowAnyMethod() //AllowAllMethods;
- //.WithHeaders("Accept", "Content-type", "Origin", "X-Custom-Header"); //AllowSpecificHeaders;
- .AllowAnyHeader(); //AllowAllHeaders;
- })
- );
With Origin
- Allow Specific Origin
builder.WithOrigins("http://localhost:4456")
- Allow Multiple Origins
builder.WithOrigins("http://localhost:4456", "http://localhost:4457")
- Allow All Origins
builder.AllowAnyOrigin()
With Methods
- Allow Specific Methods
builder.WithMethods("GET", "PUT", "POST", "DELETE")
- Allow All Methods
builder.AllowAnyMethod()
With Headers
- Allow Specific Headers
builder.WithHeaders("Accept", "Content-type", "Origin", "X-Custom-Header")
- Allow All Headers
builder.AllowAnyHeader()
After that, we have enabled CORS for your application, using an extension method “UseCors“.
Startup.cs Configure- //Enable CORS policy "AllowCors"
- app.UseCors("AllowCors");
- publicclassStartup {
- public Startup(IHostingEnvironmentenv) {
- var builder = newConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($ "appsettings.{env.EnvironmentName}.json", optional: true);
- if (env.IsEnvironment("Development")) {
- // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
- builder.AddApplicationInsightsSettings(developerMode: true);
- }
- builder.AddEnvironmentVariables();
- Configuration = builder.Build();
- }
- publicIConfigurationRoot Configuration {
- get;
- }
- // This method gets called by the runtime. Use this method to add services to the container
- publicvoidConfigureServices(IServiceCollection services) {
- //Add database services.
- varconnectionString = this.Configuration.GetConnectionString("dbConn");
- services.AddDbContext < PhoneBookContext > (options => options.UseSqlServer(connectionString));
- // Add framework services.
- services.AddApplicationInsightsTelemetry(Configuration);
- services.AddMvc();
- //Add CORS services.
- //services.Configure<MvcOptions>(options =>
- //{
- // options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
- //});
- services.AddCors(
- options => options.AddPolicy("AllowCors",
- builder => {
- builder
- //.WithOrigins("http://localhost:4456") //AllowSpecificOrigins;
- //.WithOrigins("http://localhost:4456", "http://localhost:4457") //AllowMultipleOrigins;
- .AllowAnyOrigin() //AllowAllOrigins;
- //.WithMethods("GET") //AllowSpecificMethods;
- //.WithMethods("GET", "PUT") //AllowSpecificMethods;
- //.WithMethods("GET", "PUT", "POST") //AllowSpecificMethods;
- .WithMethods("GET", "PUT", "POST", "DELETE") //AllowSpecificMethods;
- //.AllowAnyMethod() //AllowAllMethods;
- //.WithHeaders("Accept", "Content-type", "Origin", "X-Custom-Header"); //AllowSpecificHeaders;
- .AllowAnyHeader(); //AllowAllHeaders;
- })
- );
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
- publicvoid Configure(IApplicationBuilder app, IHostingEnvironmentenv, ILoggerFactoryloggerFactory) {
- loggerFactory.AddConsole(Configuration.GetSection("Logging"));
- loggerFactory.AddDebug();
- app.UseApplicationInsightsRequestTelemetry();
- app.UseApplicationInsightsExceptionTelemetry();
- app.UseMvc();
- //Enable CORS policy "AllowCors"
- app.UseCors("AllowCors");
- }
- }





Bryian TanPosted Aug 16, 2017, 12:04 AM
Good stuff. Thanks.
Prasanna MuraliPosted Oct 28, 2016, 8:14 AM
Nice post...