In this article I will explain the following things:
  1. What is CORS
  2. Same origin vs Different origin
  3. CORS Setup
  4. Implementation
    1. Action level
    2. Controller level
    3. Globally
  5. Disable CORS
  6. CORS policy options
  7. Multiple CORS

What is CORS

In this article we will see in detail how to setup and implement CORS in a dotnet core application.
The full name of CORS is Cross Origin Resource Sharing. It is a W3C standard that allows a server to make cross-domain calls from the specified domains, while rejecting others By default due to browser security it prevents a web page from making one domain Ajax request to another domain.
This security in the software term is called the same-origin policy and does not allow a suspensive site attack for reading sensitive data from another site.The AJAX call will return the error message:
No ‘Access-Control-Allow-Origin’ header is present on the requested resource
But so many times we are using multipe domain applications which is reqired to call from one domain to other domain; in this case we need to allow cross origin policy.
Then in this case if the browser supports CORS, it sets the headers automatically for cross-origin requests."
If all the things will work as expected with the server, then the server adds "Access-Control-Allow-Origin" header in the response.
When the response is not included in the header Access-Control-Allow-Origin, then this kind of request will be fail.

Same origin vs Different origin

Two URLs have the same origin if both belong to the same domain.
These two URLs have the same origin,
The following URLs have different origins than the previous two URLs,

CORS Setup

To se tup the CORS we need to go with the following steps
Install Nuget package: Microsoft.AspNetCore.Cors.
For the installation we have 2 way to do it.
Using package manager,
PM> Install-package Microsoft.AspNetCore.Cors
Using application Nuget search.
After nuget package is installed you will be able to see it  in your application package library.
Configure CORS startup class inside the ConfigureService method. 
  1. public void ConfigureServices(IServiceCollection services)  
  2. services.AddCors(options =>  
  3. {  
  4.    options.AddPolicy("Policy11",  
  5.    builder => builder.WithOrigins(""));  
  6. });  
Enable CORS using middleware in the Configure method.
  1. public void Configure(IApplicationBuilder app)  
  2. {  
  3.    app.UseCors("AllowMyOrigin");  
  4. }  
We must use UseCors before the UseMvc call then only the CORS middleware will execute before any other endpoints.


To enable CORS there are  three ways to do so:
  • Middleware using a named policy or default policy.
  • Using endpoint routing.
  • Using [EnableCors] attribute.
When you use UseCors and UseResponseCaching both, then UseCors must be called before UseResponseCaching.
Middleware uses a named policy or default policy.
This following code enables the default CORS policy,
  1. public class Startup {  
  2.     public void ConfigureServices(IServiceCollection services) {  
  3.         services.AddCors(options => {  
  4.             options.AddDefaultPolicy(builder => {  
  5.                 builder.WithOrigins("""");  
  6.             });  
  7.         });  
  8.         services.AddControllers();  
  9.     }  
  10.     public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {  
  11.         if (env.IsDevelopment()) {  
  12.             app.UseDeveloperExceptionPage();  
  13.         }  
  14.         app.UseRouting();  
  15.         app.UseCors();  
  16.         app.UseEndpoints(endpoints => {  
  17.             endpoints.MapControllers();  
  18.         });  
  19.     }  
  20. }  
The above code applies the default CORS policy to all controllers.
Using endpoint routing.
Using endpoint routing, CORS can be apply per-endpoint basis using the RequireCors.
  1. public class Startup {  
  2.     readonly string allowCors = "_myOrigins";  
  3.     public void ConfigureServices(IServiceCollection services) {  
  4.         services.AddCors(options => {  
  5.             options.AddPolicy(name: allowCors, builder => {  
  6.                 builder.WithOrigins("");  
  7.             });  
  8.         });  
  9.     }  
  10.     public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {  
  11.         if (env.IsDevelopment()) {  
  12.             app.UseDeveloperExceptionPage();  
  13.         }  
  14.         app.UseRouting();  
  15.         app.UseCors();  
  16.         app.UseAuthorization();  
  17.         app.UseEndpoints(endpoints => {  
  18.             endpoints.MapGet("/foo", context => context.Response.WriteAsync("foo")).RequireCors(MyAllowSpecificOrigins);  
  19.         });  
  20.     }  
  21. }  
Using [EnableCors] attribute.
Sometimes we need to allow CORS for spcific end points.
This [EnableCors] attribute allow CORS for selected endpoints, so it will not impact the all endpoints,
This attribute will be applied on the following places:
  • Global
  • Controller
  • action method
Action Level 
  1. public class TestController: ControllerBase {  
  2.         [EnableCors("Policy2")]  
  3.         [HttpGet]  
  4.         public ActionResult < IEnumerable < string >> Get() {  
  5.                 return new string[] {  
  6.                     "apple",  
  7.                     "mango"  
  8.                 };  
  9.             }  
  10.             [EnableCors("Policy1")]  
  11.             [HttpGet("{id}")]  
  12.         public ActionResult < string > Get(int id) {  
  13.             return "test"  
  14.         }  
Controller Level
To apply the CORS policy for a particular controller we need to add the [EnableCors] attribute at controller level.
  1. [EnableCors("Policy1")]  
  2. public class HomeController : Controller  
  3. {  
  4. }  
Global level
You can enable CORS globally for all controllers by adding the CorsAuthorizationFilterFactory filter in the ConfigureServices method,
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddMvc();  
  3.     services.Configure < MvcOptions > (options => {  
  4.         options.Filters.Add(new CorsAuthorizationFilterFactory("Policy1"));  
  5.     });  
  6. }   
The CORS order of execution is: action, controller, global. Action-level policies execute over controller-level policies, and controller-level policies take precedence over global policies.

Disable CORS

Sometimes we need to disable CORS for a controller level or an action length, then we need to use the inbuilt provided [DisableCors] attribute.
  1. [DisableCors]  
  2. public IActionResult About()  
  3. {  
  4.    return View();  
  5. }  

CORS policy options

There are many more options availables that we can set in CORS policy,
  • allowed origins
  • allowed HTTP methods
  • allowed request headers
  • response headers
  • Credentials in CORS requests
  • preflight expiration time

Multiple CORS

Sometimes we need to add multiple CORS.
The following code will create two CORS policies:
  1. public void ConfigureServices(IServiceCollection services) {  
  2.         services.AddCors(options => {  
  3.             options.AddPolicy("Policy1", builder => {  
  4.                 builder.WithOrigins("");  
  5.             });  
  6.             options.AddPolicy("Policy2", builder => {  
  7.                 builder.WithOrigins("").AllowAnyHeader().AllowAnyMethod();  
  8.             });  
  9.         });  
Thank you for taking your valuable time to read the full article.  

Similar Articles