.NET Core 2.x升级至.NET 6后ASP Web API的CORS问题
.NET 6带认证场景下的通配符CORS配置方案
问题背景
将ASP.NET Web API从.NET Core 2.x升级到.NET 6后,出现CORS相关报错:
Access to fetch at <url1> from origin <url2> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
原.NET 2.2代码中同时使用AllowAnyOrigin()和AllowCredentials()可以正常运行,但.NET 6中必须注释AllowCredentials()才能避免冲突,现需解决带认证(需保留AllowCredentials())场景下的“通配符”CORS需求。
问题根源
.NET Core 3.0及后续版本(包括.NET 6)严格遵循W3C CORS规范:当响应包含Access-Control-Allow-Credentials: true时,Access-Control-Allow-Origin不能设置为通配符*,必须是具体的请求源。而AllowAnyOrigin()本质是设置*,因此和AllowCredentials()冲突,导致CORS响应头不生效,触发报错。.NET Core 2.x未严格执行该规范,所以之前的配置可以正常运行。
解决方案
方案1:动态允许所有请求源(模拟“通配符”效果)
通过SetIsOriginAllowed动态返回当前请求的Origin,替代AllowAnyOrigin(),既实现允许任意源,又符合CORS规范:
ConfigureServices配置
services.AddCors(options => { options.AddPolicy("AllowAllWithCredentials", policy => { policy.AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .SetIsOriginAllowed(_ => true); // 允许所有请求源,动态返回请求的Origin }); }); services.AddMvc(o => o.EnableEndpointRouting = false) .AddNewtonsoftJson(options => { /* 你的配置 */ });
Configure配置
app.UseCors("AllowAllWithCredentials"); // 后续中间件和配置保持不变 app.UseMiddleware<OptionsMiddleware>(); app.UseMiddleware<BearerTokenMiddleware>(); app.UseWebSockets(); app.UseMvc();
方案2:配置具体允许的源列表(更安全)
如果知道前端的具体源,直接配置到允许列表中,这是更安全的做法:
ConfigureServices配置
services.AddCors(options => { options.AddPolicy("SpecificOriginsWithCredentials", policy => { policy.WithOrigins("https://your-frontend-domain.com", "https://another-domain.com") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); });
Configure配置
app.UseCors("SpecificOriginsWithCredentials"); // 后续中间件和配置保持不变 app.UseMiddleware<OptionsMiddleware>(); app.UseMiddleware<BearerTokenMiddleware>(); app.UseWebSockets(); app.UseMvc();
注意事项
- 确保
UseCors()在UseMvc()、认证中间件等之前调用,否则CORS头可能无法正确添加。 - 如果使用端点路由(未设置
EnableEndpointRouting = false),需要在MapControllers()时指定CORS策略,例如:app.MapControllers().RequireCors("AllowAllWithCredentials");
内容的提问来源于stack exchange,提问作者James Harcourt
相关产品推荐
相关产品推荐

