首页  >  文章  >  后端开发  >  ASP.NET Core 中 CORS 配置的 EnableCors 属性中的策略名称代表什么?

ASP.NET Core 中 CORS 配置的 EnableCors 属性中的策略名称代表什么?

DDD
DDD原创
2024-10-23 13:34:30813浏览

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

了解 ASP.NET Core 中的 CORS 配置

跨源请求共享 (CORS) 允许一个域中的资源被另一个域请求。在 ASP.NET Core Web API 上启用 CORS 对于跨域通信至关重要。

EnableCors 属性中的 PolicyName 是什么?

EnableCors 属性需要一个 policyName 参数字符串类型。此策略名称标识特定的 CORS 策略,该策略定义来自特定来源的请求的规则。

在 ASP.NET Core 中配置 CORS

对于 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>

对于 ASP.NET Core 3.1 和 5.0:

ConfigureServices 中的配置:

<code class="csharp">public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("MyPolicy", builder =>
        {
            builder.WithOrigins("http://example.com")
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });
    });
}</code>

政策的应用:

  • 关于控制器和操作:
<code class="csharp">[EnableCors("MyPolicy")]
public class MyController : Controller
{
    // ...
}</code>
  • 致所有请求:
<code class="csharp">public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");
    
    // ...
}</code>

通过配置策略并相应应用它,您可以在 ASP.NET Core Web API 中启用跨域请求。

以上是ASP.NET Core 中 CORS 配置的 EnableCors 属性中的策略名称代表什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn