c# - 如何在 asp.net core 3.1 中为每种类型的请求启用 Cors

标签 c# asp.net-core cors asp.net-core-3.0 asp.net-core-3.1

如何在 asp.net core 3.1 中为每种类型的请求启用 Cors?

我正在关注 MS Docs但它们似乎不起作用。

注意:我能够为特定域实现 cors,但不能为每个域实现。例如,我已将以下配置应用于我的项目:

  1. ConfigureServices(); 方法中我添加了:

    services.AddCors();

  2. Configure() 方法中我添加了:

    app.UseCors( builder => { build 者 .WithOrigins() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); });

但是当我尝试从另一个 url 使用 jQuery 访问 API 时,我得到:

Access to XMLHttpRequest at 'https://localhost:44314/Reservation' from origin 'https://localhost:44361' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

现在,如果我将 URL 放入 WithOrigins() 方法中,我就可以访问 API:

app.UseCors(builder =>
{
    builder
    .WithOrigins("https://localhost:44361")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials();
});

我的问题是如何让每个 URL(即域、子域等)不受限制地访问 API。应用 * 不起作用。

请帮忙。

最佳答案

您需要允许您使用以下方式执行的任何来源:

builder.AllowAnyOrigin()

具有 AllowCredentials 的任何来源

不允许从任何来源发送凭据是设计使然。

可以通过使用以下方法解决这个问题

builder.SetIsOriginAllowed(_ => true)

我认为这不是一个很好的解决方案,因为它消除了 useCredentials() 的好处。

注意

在 header 中发送 JWT 不需要

useCredentials。它用于是否需要在请求中发送 cookie。允许任何来源并启用 useCredentials 会导致安全漏洞,这就是默认情况下不允许的原因。

有关更多信息,您应该阅读

What exactly does the Access-Control-Allow-Credentials header do?

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

关于c# - 如何在 asp.net core 3.1 中为每种类型的请求启用 Cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60636051/

相关文章:

CORS 策略不允许和阻止 Angular 前端 POST 到 Golang 后端方法

c# - Selenium(chrome) 在导航时崩溃

c# - 在wpf中绘制垂直线

c# - Orchard 项目模块出现错误 : No persister for: SomePartRecord

c# - Docker-Compose YML 与 ASP.NET Core 2.2 Web API 和 SQL Server 2017

html - CORS HEADERS 仅在飞行前或每次请求时出现

c# - Automapper:ForMember 中的复杂 if else 语句

c# - ViewData 未传递到 ASP.NET Core 2.1 中的布局

在 Visual Studio Code 中运行的 .Net Core MVC 应用程序找不到 View

tomcat - 将 CORS 过滤器应用于 Tomcat 4XX 响应