Enabling CORS In ASP.NET Core API Applications

What is CORS?

 
Cross-Origin Resource Sharing (CORS) manages the cross-origin requests. Unlike same-origin policy, CORS allows making a request from one origin to another. CORS allows the servers to specify who can access the resource on the server from outside.
 
The origin is made up of three parts - the protocol, host, and the port number.
 
This is in continuation of my last article (create RESTful API using ASP.NET Core with Entity Framework Core) so I highly recommend you to go through my previous article for the basic set up of an ASP.NET Core application.
 

Cross Domain call

 
Before enabling the CORS, let’s see how the cross-domain call is restricted. Let’s create an ASP.NET Core web application.
 
Step1 
 
Open Visual Studio, click on NEW ->Project. Select ASP.NET Web Application template under Web, as shown in the below figure.
 
Enabling CORS In ASP.NET Core API Application
 
Step 2
 
Select web application (Model-View-Controller) template, as shown in the below figure,
 
Enabling CORS In ASP.NET Core API Application
 
Step 3
 
Click OK. This will create a web application with a default template.
 
Step 4
 
Go to the Index.cshtml page and add the below code and run the application.
  1. <script>  
  2.    $.ajax({  
  3.        url: "https://localhost:44348/api/Libraries/GetAllAuthor", 
  4.        success: function (result) {  
  5.            console.log(result);  
  6.     }  
  7.     })  
  8. </script> 
From the above code, you can notice the AJAX call I made to access the API which is not from the same origin. This is from the ASP.NET Core API application which is created in my last article.
 
Testing the API in the Postman tool.
 
Enabling CORS In ASP.NET Core API Application
 
In the browser console, you will get an error message as shown in the below figure.
 
Enabling CORS In ASP.NET Core API Application 
 
Now it’s time to Enable CORS in our API application so that we can access it from a different origin.
 

Enable CORS in ASP.NET Core API Application

 
Enabling CORS Globally
 
Open the ASP.NET Core API application which we created in my last article.
 
Go to Startup.cs file and add the below code in Configure method, which will inject CORS into a container.
  1. app.UseCors(options => options.AllowAnyOrigin());  
Add the below code in ConfigureServices method,   
  1. services.AddCors(c =>  
  2. {  
  3.     c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
  4. });  
The above code tells that the API’s can be accessed from any origin globally.
 
Run the application,
Enabling CORS In ASP.NET Core API Application
 
From the above figure you can notice we got a response from the API successfully and the response it printed in browser console was as expected.
 

Enabling for origin

 
Go to Startup.cs file and add the below code in Configure method, 
  1. app.UseCors(options=>options.WithOrigins("https://localhost:44342"));  
Add the below code in ConfigureServices method
  1. services.AddCors(c =>  
  2.             {  
  3.                 c.AddPolicy("AllowOrigin", options => options.WithOrigins("https://localhost:44342"));  
  4.             });  
Go to controller and decorate the action with Enable CORS attribute, as given below,
  1. // GET: api/Libraries/GetAllAuthor  
  2.      [HttpGet]  
  3.      [Route("GetAllAuthor")]  
  4.      [EnableCors("AllowOrigin")]  
  5.      public IActionResult GetAllAuthor()  
  6.      {  
  7.          IEnumerable<Author> authors = _libraryRepository.GetAllAuthor();  
  8.          return Ok(authors);  
  9.      }  
Now this API can be accessed only from the origin https://localhost:44342.
 
We can also define EnableCors at the controller level so that all the actions under this controller can be accessed from the origin https://localhost:44342
  1.   [Route("api/Libraries")]  
  2.     [ApiController]  
  3.     [EnableCors("AllowOrigin")]  
  4.     public class LibrariesController : ControllerBase  
  5.     {  
  6.         private readonly ILibraryRepository<Author> _libraryRepository;  
  7.          
  8.   
  9.        
  10.         public LibrariesController(ILibraryRepository<Author> libraryRepository)  
  11.         {  
  12.             _libraryRepository = libraryRepository;  
  13.         }  
  14.   
  15.         // GET: api/Libraries/GetAllAuthor  
  16.         [HttpGet]  
  17.         [Route("GetAllAuthor")]  
  18.           
  19.         public IActionResult GetAllAuthor()  
  20.         {  
  21.             IEnumerable<Author> authors = _libraryRepository.GetAllAuthor();  
  22.             return Ok(authors);  
  23.         }  
  24. }  
  25. }  

Conclusion

 
We saw how to enable the CORS in ASP.NET Core API applications, will see more about ASP.NET Core in my future articles. I hope you have enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcomed.