CORS in ASP.NET CORE

1 minute read | March 27, 2017

In my spare time I am writing applications with technologies, which are newer than my job project’s ones. So, I decided to build a simple app using ASP.NET CORE and AngularJs (version 2).

In the time of writting this project, I was getting a strange behaivor of my requests from javascript to server-side.

    let body: any = {"Email": "value1", "Password": "value2"};
    let url = "http://localhost:5000/api/user/login";
    let response: any;
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    this.http.post(url, body, options).subscribe(
      data => {
        response = data
      },
      err => console.error(err),
      () => {
        console.log(response)
      });

My code didn’t want to set custom Content-type headers. When I send a request, I got 415 (Unsupported Media Type) and No 'Access-Control-Allow-Origin' header is present exception in console.

Errors’ screenshot

Screenshot of Google Chrome's console

Searching for solution

First of all, I thought about problems with HttpModule of Angular. I even created a stackoverflow question. Then, I started to think that the problem may be at the server side. And it was. I had forgotten to set up CORS settings for for my back-end app.

Configuring CORS for ASP.NET CORE

First of all installing of Microsoft.AspNetCore.Cors is required. You can do this by GUI or just run Install-Package Microsoft.AspNetCore.Cors in Package Manager Console. Then you should modify your Startup.cs.

Step 1. Modify ConfigureServices method

You need add some code to your ConfigureServices method

 public void ConfigureServices(IServiceCollection services)
 {
    //CORS
    var corsBuilder = new CorsPolicyBuilder();
    corsBuilder.AllowAnyHeader();
    corsBuilder.AllowAnyMethod();
    corsBuilder.AllowAnyOrigin(); // For everyone
	
    // If you want to set up a special origin
    //corsBuilder.WithOrigins("http://localhost:1111"); 

    corsBuilder.AllowCredentials();

    services.AddCors(options =>
    {
        options.AddPolicy("MyCorsPolicy", corsBuilder.Build());
    });

	// other stuff
  }

Step 2. Modify Configure method

Then you need to modify Configure method

public void Configure(IApplicationBuilder app, 
					  IHostingEnvironment env, 
					  ILoggerFactory loggerFactory)
{
    app.UseCors("MyCorsPolicy");	
	// other stuff	
    app.UseMvc();
}

Please Note: It’s important to put app.UseCors("MyCorsPolicy") before app.UseMvc(). For details see official docs.

Conclusion

That’s all. I’ll be happy, If this article helps you.

Docs about CORS in ASP.NET CORE

Leave a Comment