Home >Backend Development >C++ >What Does Policy Name Represent in the EnableCors Attribute for CORS Configuration in ASP.NET Core?
Understanding CORS Configuration in ASP.NET Core
Cross Origin Request Sharing (CORS) allows resources from one domain to be requested by another domain. Enabling CORS on an ASP.NET Core Web API is crucial for cross-domain communication.
What is PolicyName in EnableCors Attribute?
The EnableCors attribute requires a policyName parameter of type string. This policyName identifies a specific CORS policy that defines the rules for requests from specific origins.
Configuring CORS in ASP.NET Core
For ASP.NET Core 6:
<code class="csharp">var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(options => { options.AddPolicy("MyPolicy", builder => { builder.WithOrigins("http://example.com", "http://www.contoso.com"); }); }); app.UseCors("MyPolicy");</code>
For ASP.NET Core 3.1 and 5.0:
Configuration in ConfigureServices:
<code class="csharp">public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("MyPolicy", builder => { builder.WithOrigins("http://example.com") .AllowAnyMethod() .AllowAnyHeader(); }); }); }</code>
Application of Policy:
<code class="csharp">[EnableCors("MyPolicy")] public class MyController : Controller { // ... }</code>
<code class="csharp">public void Configure(IApplicationBuilder app) { app.UseCors("MyPolicy"); // ... }</code>
By configuring a policy and applying it accordingly, you can enable cross-domain requests in your ASP.NET Core Web API.
The above is the detailed content of What Does Policy Name Represent in the EnableCors Attribute for CORS Configuration in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!