Home > Backend Development > C++ > How to Implement Cross-Origin Resource Sharing (CORS) in ASP.NET Core Web API?

How to Implement Cross-Origin Resource Sharing (CORS) in ASP.NET Core Web API?

Linda Hamilton
Release: 2025-01-24 18:42:13
Original
740 people have browsed it

How to Implement Cross-Origin Resource Sharing (CORS) in ASP.NET Core Web API?

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>
Copy after login

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>
Copy after login

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>
Copy after login
MyPolicy can be defined in ConfigureServices:

<code class="language-csharp">services.AddCors(options =>
{
    options.AddPolicy("MyPolicy",
        policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});</code>
Copy after login
This will enable CORS for all controllers and actions, no separate controller or action level configuration is required.

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>
Copy after login
This will add X-My-Custom-Header to the list of headers allowed to be made public.

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>
Copy after login
This middleware will add the specified headers to all responses, effectively enabling CORS for all requests.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template