You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮调用PhotosController时遭CORS策略拦截,如何解决?

CORS 凭据模式下的跨域问题解决方法

你的问题核心在于:当请求的凭据模式为include(即请求携带Cookie、HTTP认证或客户端SSL证书这类凭据)时,浏览器禁止后端用通配符*作为Access-Control-Allow-Origin的取值,必须明确指定允许的源。你之前用的AllowAnyOrigin()本质就是设置*,这和请求的凭据模式冲突,所以报错。

解决步骤:

  • 明确指定允许的前端源,替换通配符配置:

    app.UseCors(x => x
        .WithOrigins("https://localhost:4200") // 填写你的前端实际地址
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials()); // 必须添加此项,允许传递凭据
    
  • 如果需要支持多个源,可以从配置文件读取:

    1. 在appsettings.json中添加允许的源列表:
      "CorsOrigins": [
        "https://localhost:4200",
        "https://prod-frontend.example.com"
      ]
      
    2. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:20:23