点击按钮调用PhotosController时遭CORS策略拦截,如何解决?
CORS 凭据模式下的跨域问题解决方法
你的问题核心在于:当请求的凭据模式为include(即请求携带Cookie、HTTP认证或客户端SSL证书这类凭据)时,浏览器禁止后端用通配符*作为Access-Control-Allow-Origin的取值,必须明确指定允许的源。你之前用的AllowAnyOrigin()本质就是设置*,这和请求的凭据模式冲突,所以报错。
解决步骤:
明确指定允许的前端源,替换通配符配置:
app.UseCors(x => x .WithOrigins("https://localhost:4200") // 填写你的前端实际地址 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); // 必须添加此项,允许传递凭据如果需要支持多个源,可以从配置文件读取:
- 在
appsettings.json中添加允许的源列表:"CorsOrigins": [ "https://localhost:4200", "https://prod-frontend.example.com" ] - 在Program.cs中读取配置并设置CORS:
var allowedOrigins = builder.Configuration.GetSection("CorsOrigins").Get<string[]>(); app.UseCors(x => x .WithOrigins(allowedOrigins) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials());
- 在
另外要确认前端请求是否开启了withCredentials:比如Angular的HttpClient请求需添加配置项:
this.http.get('https://localhost:5001/api/photos/1/photos', { withCredentials: true });
内容的提问来源于stack exchange,提问作者Alejandro
相关产品推荐
相关产品推荐

