Enabling CORS in ASP.NET Core Web API: Complete Guide
Cross-Origin Resource Sharing (CORS) is a mechanism that allows web browsers to make cross-origin HTTP requests, typically to a different domain than the browser's current origin. Enabling CORS is essential to ensure seamless communication between front-end applications and back-end web APIs hosted on different domains or ports.
Enable CORS in Startup.cs
The preferred way to enable CORS in ASP.NET Core is through the Startup.cs file. In the ConfigureServices method, add the following lines to install the CORS package and configure the CORS service:
<code class="language-csharp">services.AddCors(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);</code>
Next, in the Configure method, configure the CORS middleware before calling app.UseMvc():
<code class="language-csharp">app.UseCors(options => options.WithOrigins("http://example.com").AllowAnyMethod());</code>
This will allow HTTP methods from the specified source (in this case "https://www.php.cn/link/63e6bc520edcbaa95446b5690d989f30
Global configuration CORS
If you want to enable CORS globally for all controllers and actions, you can add the [EnableCors] attribute to the Startup.cs file:
<code class="language-csharp">[assembly: EnableCors(typeof(MyPolicy))]</code>
<code class="language-csharp">services.AddCors(options => { options.AddPolicy("MyPolicy", policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); });</code>
Add custom header
If you need to specify other custom headers in the CORS configuration, you can modify the options object in the app.UseCors statement:
<code class="language-csharp">app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader() .WithExposedHeaders("X-My-Custom-Header"));</code>
Force method using manual header addition
As an alternative to using the built-in CORS middleware, you can use the middleware to manually add the required headers to each response. This method is less recommended, but can be useful in some situations, especially when using authorization headers.
<code class="language-csharp">app.Use(async (context, next) => { context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE"); context.Response.Headers.Add("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"); await next(); });</code>
Conclusion
There are several ways to enable CORS in ASP.NET Core, depending on your specific requirements. By following the steps outlined in this guide, you can ensure seamless cross-origin communication between front-end applications and back-end web APIs, allowing data and functionality to be shared across domains.The above is the detailed content of How to Implement Cross-Origin Resource Sharing (CORS) in ASP.NET Core Web API?. For more information, please follow other related articles on the PHP Chinese website!