Problem
How to implement Cross-Origin Requests (CORS) in ASP.NET Core.
Solution
Create an empty project and update the Startup to configure CORS services and middleware,
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddCors(options =>
- {
- options.AddPolicy("fiver",
- policy => policy.WithOrigins("http://localhost:21314"));
- });
-
- services.AddMvc();
- }
-
- public void Configure
- (IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseCors("fiver");
-
- app.UseMvcWithDefaultRoute();
- }
Discussion
To allow clients from a different origin to access your ASP.NET Core Web API, you’ll need to allow Cross-Origin Requests (CORS). Here same origin means clients who have identical schemes, hosts and ports.
There are two main methods of achieving this,
Using Middleware
To enable CORS for the entire Web API, you could use middleware,
- Add CORS services and setup named policy.
- Use middleware passing in policy name.
Note
The above code in the Solution section demonstrates this method.
Using MVC
To have more control over controllers and actions that enable/disable CORS, you could use attributes and filters in MVC,
- Add CORS services and setup named policy.
- To enable CORS for,
- Actions/Controller: Use [EnableCors]
- Globally: Add CorsAuthorizationFilterFactory to MVC filters. Use [DisableCors] attribute to disable CORS for individual controllers and actions.
Below code adds CORS using attributes. First configure CORS in Startup,
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddCors(options =>
- {
- options.AddPolicy("fiver",
- policy => policy.WithOrigins("http://localhost:21314"));
- });
-
- services.AddMvc();
- }
-
- public void Configure
- (IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseMvcWithDefaultRoute();
- }
Then use attributes on the controller/action,
- [Route("movies")]
- [EnableCors("fiver")]
- public class MoviesController : Controller
- {
- [HttpGet]
- public IActionResult Get()
- {
- return Content("List of Movies");
- }
-
- [HttpGet("{id}")]
- [DisableCors]
- public IActionResult Get(int id)
- {
- return Content($"Movie {id}");
- }
- }
Below code adds CORS globally using MVC filters,
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddCors(options =>
- {
- options.AddPolicy("fiver",
- policy => policy.WithOrigins("http://localhost:21314"));
- });
-
- services.AddMvc(options =>
- {
- options.Filters.Add(new CorsAuthorizationFilterFactory("fiver"));
- });
- }
-
- public void Configure
- (IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseMvcWithDefaultRoute();
- }
For information on various policy options, please refer to documentation here.
Source Code
GitHub