簡體   English   中英

如何在 ASP.NET Core 中啟用 CORS

[英]How to enable CORS in ASP.NET Core

我正在嘗試在我的 ASP.NET Core Web API 上啟用跨源資源共享,但我被卡住了。

EnableCors屬性接受string類型的policyName作為參數:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

policyName是什么意思,如何在 ASP.NET Core Web API 上配置CORS

對於 ASP.NET Core 6:

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

// services.AddResponseCaching();

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

有關更多示例,請參閱官方文檔


對於 ASP.NET Core 3.1 和 5.0:

您必須在應用程序啟動時在ConfigureServices方法中配置 CORS 策略:

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

    // ...
}

builder中的CorsPolicyBuilder允許您根據需要配置策略。 您現在可以使用此名稱將策略應用於控制器和操作:

[EnableCors("MyPolicy")]

或將其應用於每個請求:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");

    // ...

    // This should always be called last to ensure that
    // middleware is registered in the correct order.
    app.UseMvc();
}

適用於 .NET Core 1 和 .Net Core 2

如果使用.Net-Core 1.1

不幸的是,在這種特定情況下,文檔非常混亂。 所以我會讓它變得非常簡單:

  • Microsoft.AspNetCore.Cors nuget 包添加到您的項目中

  • ConfigureServices方法中,添加services.AddCors();

  • Configure方法中,在調用app.UseMvc()app.UseStaticFiles()之前,添加:

     app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials());

而已。 每個客戶端都可以訪問您的 ASP.NET Core 網站/API。


如果使用.Net-Core 2.0

  • Microsoft.AspNetCore.Cors nuget 包添加到您的項目中

  • ConfigureServices方法中,調用services.AddMvc()之前,添加:

     services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); });
  • (重要)Configure方法中,調用app.UseMvc()之前,添加app.UseCors("AllowAll");

    "AllowAll"是我們需要在app.UseCors中提及的策略名稱。 它可以是任何名稱。

根據Henk 的回答,我已經能夠提出特定的域、我想要允許的方法以及我想要啟用 CORS 的標頭:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
         options.AddPolicy("AllowSpecific", p => p.WithOrigins("http://localhost:1233")
                                                   .WithMethods("GET")
                                                   .WithHeaders("name")));
    services.AddMvc();
}

用法:

[EnableCors("AllowSpecific")]

如下所示與.NET Core 3.1一起使用

  1. 確保將UseCors代碼app.UseRouting();之間app.UseAuthentication();
app.UseHttpsRedirection();

app.UseRouting();
app.UseCors("CorsApi");

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
    endpoints.MapControllers();
});
  1. 然后將此代碼放在ConfigureServices方法中
services.AddCors(options =>
{
    options.AddPolicy("CorsApi",
        builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
            .AllowAnyHeader()
            .AllowAnyMethod());
});
  1. 在基本控制器上方,我放置了這個
[EnableCors("CorsApi")]
[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase

現在我所有的控制器都將從BaseController繼承並啟用 CORS

如果你在 IIS 上托管,一個可能的原因是你得到這個是因為 IIS 阻止了OPTIONS動詞。 因為這個,我花了將近一個小時:

一個明顯的跡象是您在OPTIONS請求期間收到404錯誤。

要解決此問題,您需要明確告訴 IIS不要阻止OPTIONS請求。

轉到請求過濾:

IIS 請求過濾

確保允許 OPTIONS:

確保 OPTIONS 為 True

或者,只需使用以下設置創建一個web.config

<system.webServer>
    <security>
        <requestFiltering>
            <verbs>
                <remove verb="OPTIONS" />
                <add verb="OPTIONS" allowed="true" />
            </verbs>
        </requestFiltering>
    </security>
</system.webServer>

特別是在帶有 SignalR 的 dotnet core 2.2 中,您必須更改

.WithOrigins("http://localhost:3000")

.SetIsOriginAllowed(isOriginAllowed: _ => true) //for all origins

代替.AllowAnyOrigin().AllowCredentials()

https://trailheadtechnology.com/break-change-in-aspnetcore-2-2-for-signalr-and-cors/

https://github.com/aspnet/AspNetCore/issues/4483

您必須在 Startup.cs 類中進行配置

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAnyOrigin",
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
    });

    services.Configure<MvcOptions>(options => {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
    });            
}

您可以通過三種方式啟用 CORS:

  • 在使用命名策略或默認策略的中間件中。
  • 使用端點路由。
  • 使用[EnableCors]屬性。

使用命名策略啟用 CORS:

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                 builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        // services.AddResponseCaching();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors(CorsPolicy);

        // app.UseResponseCaching();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

使用UseResponseCaching時,必須在UseResponseCaching之前調用UseCors

使用默認策略啟用 CORS:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                     builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

使用端點啟用 CORS

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy ";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                  builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                     .RequireCors(CorsPolicy)
        });
    }
}

使用屬性啟用 CORS

你有兩個選項

  • [EnableCors]指定默認策略。
  • [EnableCors("{Policy String}")]指定命名策略。

上面提到的所有解決方法可能有效,也可能無效,在大多數情況下都無效。 我在這里給出了解決方案

目前我正在研究 Angular 和 Web API(.net Core) 並遇到下面解釋的 CORS 問題

上面提供的解決方案將始終有效。 對於“OPTIONS”請求,確實有必要啟用“匿名身份驗證”。 使用此處提到的解決方案,您不必執行上述所有步驟,例如 IIS 設置。

無論如何,有人將我上面的帖子標記為與這篇文章重復,但我可以看到這篇文章只是為了在 ASP.net Core 中啟用 CORS,但我的帖子與在 ASP.net Core 和 Angular 中啟用和實現 CORS 有關。

如果您收到錯誤“請求的資源上不存在'Access-Control-Allow-Origin'標頭”。 特別是對於PUTDELETE請求,您可以嘗試在 IIS 上禁用 WebDAV。

顯然,WebDAVModule 默認啟用,默認禁用 PUT 和 DELETE 請求。

要禁用 WebDAVModule,請將其添加到您的 web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

第 1 步:我們的項目中需要 Microsoft.AspNetCore.Cors 包。 要安裝,請轉到工具 -> NuGet 包管理器 -> 管理 NuGet 包以獲取解決方案。 搜索 Microsoft.AspNetCore.Cors 並安裝包。

第 2 步:我們需要將 CORS 注入到容器中,以便應用程序可以使用它。 在 Startup.cs 類中,我們進入 ConfigureServices 方法並注冊 CORS。

在此處輸入圖像描述

因此,在我們的服務器應用程序中,讓我們轉到 Controllers -> HomeController.cs 並將 EnableCors 裝飾器添加到 Index 方法(或您的特定控制器和操作):

在此處輸入圖像描述

更多詳情請點擊這里

在我設法在最瑣碎的 CORS 問題上浪費了兩個小時之后,一些故障排除技巧:

  1. 如果您看到記錄了CORS policy execution failed ...不要假設您的 CORS 策略沒有正確執行。 事實上,CORS 中間件可以正常工作,並且您的策略正在正確執行。 這條措辭糟糕的消息的唯一含義是請求的來源與任何允許的來源都不匹配( 請參閱 source ),即該請求是不被允許的。

  2. 來源檢查(從 ASP.NET Core 5.0 開始)以一種非常簡單的方式發生......即,您通過WithOrigins()提供的字符串與HttpContext.Request.Headers[Origin]中存在的字符串之間進行區分大小寫的序號字符串比較( 參見源代碼HttpContext.Request.Headers[Origin]

  3. 如果您使用尾部斜杠/設置允許的原點,或者它包含大寫字母,CORS 可能會失敗。 (就我而言,實際上我確實不小心復制了帶有斜杠的主機。)

這涵蓋了每個端點。 如果您想阻止某些端點,請使用此注釋 [DisableCors]
它在這里很好地描述了。
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

  1. app.authentication()app.routing() ) 之間添加app.usecors(policyName) ) 如果你在它上面使用app.usMvc() 。在 Configure 方法里面。

  2. 在 configureService 方法里面

services.AddCors(options => options.AddPolicy(name: mypolicy,     builder =>     { builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }));
  1. 在每個控制器中添加[EnableCors("mypolicy")]
        [EnableCors("mypolicy")] 
        [Route("api/[controller]")] [ApiController] 
        public class MyController : ControllerBase


例如:-

  namespace CompanyApi2
        {
            public class Startup
            {
                public Startup(IConfiguration configuration)
                {
                    Configuration = configuration;
                }
        
                public IConfiguration Configuration { get; }
        
                // This method gets called by the runtime. Use this //method to add services to the container.
                public void ConfigureServices(IServiceCollection services)
                {
                    services.AddCors(options =>
                        options.AddPolicy(name: mypolicy,
                            builder =>
                            {
                                builder.AllowAnyHeader().AllowAnyMethod()
                                    .AllowAnyOrigin();
                            })); //add this
                    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
                    services.AddScoped<IDatarepository, DatabaseRepository>();
                }
        
                public string mypolicy = "mypolicy";
        
                // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
                public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                {
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
                    else
                    {
                        app.UseHsts();
                    }
        
                    app.UseCors(mypolicy); //add this
                    app.UseHttpsRedirection();
                    app.UseMvc();
                }
            }
        }

最近在 azure web app 上托管 web 應用服務器時,不得不編輯 azure app cors 設置來解決問題(僅代碼沒有解決問題)

  1. 不太安全 - 啟用 Access-Control-Allow-Credentials - 將其留空並添加 * 作為允許的來源
  2. 標記 Enable Access-Control-Allow-Credentials 然后添加要允許來自的請求的域

使用 .Net Core 3.1 進行如下操作:

ConfigureServices()方法中:

 public void ConfigureServices(IServiceCollection services)
  {
   ...
   services.AddCors();
   ...
  }

Configure()方法中:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
   ...
   app.UseCors(builder =>
          builder.AllowAnyOrigin()
          .AllowAnyHeader()
          .AllowAnyMethod()
        );
   ...
  }

對於 .Net CORE 3.1 使用:

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())

注意最后的“/” - 將阻止CORS起源

builder.WithOrigins("http://example.com/","http://localhost:55233/");

會阻止

利用

builder.WithOrigins("http://example.com","http://localhost:55233"); 

對於 ASP.NET Core Web API 5

在 ConfigureServices 添加services.AddCors(); services.AddControllers();之前

在配置中添加 UseCors

app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());

對於“C# - ASP Net Core Web API (Net Core 3.1 LTS)”,它對我有用......

Startup.cs文件中:

在“ ConfigureServices ”函數中添加以下代碼:

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader());
});

注意:在“ CorsPolicy ”的情況下,您可以更改您喜歡的內容或使用“Startup”類中的全局變量。

在“配置”函數中添加以下代碼:

app.UseCors("CorsPolicy");

檢查函數的調用順序,它應該如下所示:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});          

最后在您的控制器類中,在您的函數 http 上方添加此代碼:

[EnableCors("CorsPolicy")]

例如:

[EnableCors("CorsPolicy")]
[HttpPost("UserLoginWithGoogle")]
public async Task<ActionResult<Result>> UserLoginWithGoogle([FromBody] TokenUser tokenUser)
{            
    Result result = await usersGoogleHW.UserLoginWithGoogle(tokenUser.Token);
    return new JsonResult(result);
}

注意:“CorsPolicy”必須在啟動和控制器中匹配。

祝你好運 ...

對於 Web API(ASP.Net core 6.0) 在 Program.cs 中只需在 builder.Build() 之前添加;

builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
    builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));

還添加

app.UseCors("corsapp");

安裝 nuget 包Microsoft.AspNetCore.CORS

ConfigureServices方法下的Startup.cs中,在services.AddMVC()之前添加以下代碼

services.AddCors(options =>
{
    options.AddPolicy("AllowMyOrigin", p =>
    {
        p.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

Configure方法內的Startup.cs添加app.UseCors("AllowMyOrigin"); 在調用app.UseMvc()之前

請注意,從客戶端發送請求時,請記住使用 https 而不是 http。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM