我已经将我的项目更新到 .net core 2.2,似乎 CORS 正在产生 2.1 中没有的问题。
我正在这个 URL 上运行我的应用程序:http://*:5300
我在 Startup.cs
中添加了这段代码:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
options.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
}));
services.AddMvc();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
});
app.UseAuthentication();
app.UseMvc();
}
这没有用,所以我在我的“BaseController”类上添加了 [EnableCors]
属性:
[EnableCors]
[Authorize]
[Produces("application/json")]
[Route("api/[controller]")]
public class BaseController : Controller
{
}
但我仍然收到此 CORS 错误:
Access to XMLHttpRequest at 'http://192.168.15.63:5301/api/permissions/UI' from origin 'http://192.168.15.63:5302' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
我还能做些什么来完全删除 CORS?
最佳答案
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
在使用 ASP.NET Core 响应 CORS 请求时,您不能同时使用 AllowAnyOrigin
和 AllowCredentials
。
Access to XMLHttpRequest at 'http://192.168.15.63:5301/api/permissions/UI' from origin 'http://192.168.15.63:5302' has been blocked by CORS policy
此消息显示您的服务器正在监听http://192.168.15.63:5301
,但您的客户端正在发出请求来自 http://192.168.15.63:5302
。由于端口不同,这些是不同的来源,因此使用 CORS 保护。
要使请求成功,请将您的 ASP.NET CORS 配置代码更新为如下所示:
builder.WithOrigins("http://192.168.15.63:5302")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
这会将 客户端 的来源配置为受 CORS 支持 - 当然,您可以将其作为配置选项添加到应用程序本身(使用例如 appsettings.json
),如果需要的话。
旁白:
由于您已调用 AddCors
并配置了命名策略,因此没有理由在调用 UseCors
时配置相同的策略 - 您只需传入您之前使用 AddCors
配置的策略的名称:
app.UseCors("MyPolicy");
关于c# - 如何摆脱 .net core 2.2 中的 CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53932388/