CORS in ASP.NET Core Web API

CORS is Cross-Origin Requests, by default any request from outside the domain is not allowed in Asp.Net core Web API framework.

.net Core Web Api accept request from only same domain because of same origin policy.

To enable cors or disable cors, we need to add reference of Microsoft.AspNetCore.Cors; namespace in our controller class file.

using Microsoft.AspNetCore.Cors;

[EnableCors]
public async Task<Student> Get(int id)
{
	Student student = new Student();
	
	student.StuId = id;
	student.City = "Kolkata";
	student.Cotact = "90000000";	
	return await Task.FromResult(student);
}

To enable CORS in global level, open your startup file, and add/configure following CORS middleware like example below.

How to enable CORS in ASP.NET Web API

Configure AddCors policy with AllowAnyOrigin, WithOrigins etc.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddCors(c =>
    {
	    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
	    //c.AddPolicy("AllowOrigin", options => options.WithOrigins("https://localhost:44342"));
    });
}

Configure UseCors policy with AllowAnyOrigin, WithOrigins etc.

We could have also written with following additional details, like specifying policy name and then WithMethods (which are the methods we want to allow for this particular policy)

services.AddCors(c =>
{
	c.AddPolicy(name: "CorsPolicyName1", options => options.WithOrigins("https://somedomain.com")
	 .WithMethods("put","get")
	);	
});
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
		
	app.UseAuthorization();
	app.UseCors(options => options.AllowAnyOrigin());
	//app.UseCors(options => options.WithOrigins("https://localhost:44342"));
	app.UseEndpoints(endpoints =>
	{
		endpoints.MapControllers();
	});
}

Even though we have set AddCors configuration in global level we still can set some exception for any particular web api method by using attribute on web method like EnableCors [EnableCors] or DisableCors [DisableCors].

Below is an example of how you can apply this attribute.

[HttpGet("{id}")]
[EnableCors]
public async Task<Student> Get(int id)
{
	Student student = new Student();
	
	student.StuId = id;
	student.City = "Kolkata";
	student.Cotact = "989200002";	
	return await Task.FromResult(student);
}

In global configuration with origin method we can apply multiple url to allow access, like c.AddPolicy("AllowOrigin", options => options.WithOrigins("https://domain1.com", "http://domain2.com"));

Learn more about CORS attributes.

 
Enable CORS in ASP.NET Web API
Learn Web API: creating API using C# .Net, post, update, delete, read using .net API, set security, check authentication, testing.

C# web service interview questions

Learn API development
Asp.Net C# Web API Examples | Join Asp.Net MVC Course