首頁  >  文章  >  後端開發  >  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