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.

How to enable CORS in ASP.NET Web API

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

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.

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

C# web service interview questions

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