Home  >  Article  >  Backend Development  >  What Does Policy Name Represent in the EnableCors Attribute for CORS Configuration in ASP.NET Core?

What Does Policy Name Represent in the EnableCors Attribute for CORS Configuration in ASP.NET Core?

DDD
DDDOriginal
2024-10-23 13:34:30813browse

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:

  • On Controllers and Actions:
<code class="csharp">[EnableCors("MyPolicy")]
public class MyController : Controller
{
    // ...
}</code>
  • To All Requests:
<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!

Statement:
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