I'd like to enable CORS on an API built with ASP.NET Core MVC, but all the current documents refer to earlier versions of that framework.
There are three ways to enable CORS: In middleware using a named policy or default policy. Using endpoint routing. With the [EnableCors] attribute.
Enable Cross-Origin Requests (CORS) in ASP.NET Core. Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site.
In this article, we will demonstrate how to enable CORS in .NET Core Web API for different situations. Install the CORS middleware. Register CORS middleware to the pipeline in the ConfigureServices method of Startup.cs. Enable CORS in the Configure method of Startup.cs. Enable/Disable CORS in the controllers, the action methods, or globally.
I've had success using the OWIN CORS implementation (nuget Microsoft.Owin.Cors) to enable Cors for MVC Controllers and Owin middleware, in addition to ApiControllers. Microsoft.AspNet.WebApi.Cors (using config.EnableCors () and the [EnableCors] attribute) only seems to work with ApiControllers.
Enable cross-origin requests in ASP.NET Web API 2. Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.
The notes on the new Cors features are very light, but I was able to get it working in my solution by looking at the new classes and methods. My Web API startup.cs looks like this. You can see how you can construct your origins and policies her by using the new CorsPolicy
class. And enabling CORS with the AddCors
and UseCors
methods.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //Add Cors support to the service services.AddCors(); var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy(); policy.Headers.Add("*"); policy.Methods.Add("*"); policy.Origins.Add("*"); policy.SupportsCredentials = true; services.ConfigureCors(x=>x.AddPolicy("mypolicy", policy)); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Configure the HTTP request pipeline. app.UseStaticFiles(); //Use the new policy globally app.UseCors("mypolicy"); // Add MVC to the request pipeline. app.UseMvc(); }
You can also reference the policy in the controllers with the new attributes like so
[EnableCors("mypolicy")] [Route("api/[controller]")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With