Home > Backend Development > C++ > body text

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

DDD
Release: 2024-10-23 13:34:30
Original
812 people have browsed it

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

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

Application of Policy:

  • On Controllers and Actions:
<code class="csharp">[EnableCors("MyPolicy")]
public class MyController : Controller
{
    // ...
}</code>
Copy after login
  • To All Requests:
<code class="csharp">public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");
    
    // ...
}</code>
Copy after login

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!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!