【问题标题】:Getting Error "No 'Access-Control-Allow-Origin' header is present on the requested resource"出现错误“请求的资源上不存在‘Access-Control-Allow-Origin’标头”
【发布时间】:2021-04-09 08:46:09
【问题描述】:

我使用以下方法启用了 CORS:

private readonly string CorsPolicy = "CorsPolicy";

services.AddCors(options =>
{
    options.AddPolicy(this.CorsPolicy, builder =>
    {
        builder.WithOrigins(this.Configuration.GetValue<string>("WebAppBaseUrl"))
               .AllowAnyHeader()
               .AllowAnyMethod()
               .SetIsOriginAllowed(_ => true)
               .AllowCredentials();
    });
});

appsettings.json 条目:

"WebAppBaseUrl": "https://localhost:44372/"

但只有一个 GET 请求我收到以下错误:

从源“https://localhost:44372”访问“https://localhost:44343/api/pushNotification/GetMyPushNotifications/1/1”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“访问控制-请求的资源上存在 Allow-Origin' 标头。

请注意,该项目有超过 50 个 GET 请求,并且在当前的 CORS 配置下所有这些请求都可以正常工作,只有这个特定的 GET 请求会给我这个 CORS 错误。

有什么想法吗?

【问题讨论】:

  • 请注意,CORS 已启用。所有其他请求都做得很好。只有一个人给我这个问题。

标签: c# asp.net-core .net-core cors


【解决方案1】:

在 appsettings.json 中添加 AllowedOrigins 部分,如下所示

"AllowedOrigins": {
"WebAppBaseUrl": "https://localhost:44372/" }

然后在启动注入配置中获取允许的来源列表,如下所示

string[] lstAllowedOrigins;
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        lstAllowedOrigins = Configuration.GetSection("AllowedOrigins").Get<string[]>();
    }

最后在Configure函数中添加如下中间件

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

【讨论】:

  • 这已经用我在问题中提到的另一种方式完成了。
  • @Oshadha 你试过我的答案了吗?请在应用后与我分享您的结果,因为它对我有用
  • 我没有通过服务使用,我直接在配置方法中使用了中间件
  • 是否有任何 api 与您合作或所有调用都因上述错误而失败?
  • 我有 20 多个 API 端点。除了这个,它们都可以工作。
【解决方案2】:

Microsoft 文档指出,指定的 URL 不得包含尾部斜杠 (/)。如果 URL 以 / 结尾,则比较返回 false 并且不返回标头。更改您的应用设置:

"WebAppBaseUrl": "https://localhost:44372/"

"WebAppBaseUrl": "https://localhost:44372"

【讨论】:

  • 我当然会这样做。但是,你知道为什么它只适用于这个特定的。知道为什么会这样。
【解决方案3】:

经过几天的尝试,我发现了问题。

我调用的 API 端点有 2 个端点,如下所示:

  • /getPushNotification/{userId}/{pageId}
  • /getPushNotification/{userId}

我尝试了同样的方法,如下更改它们:

  • /getPagedPushNotification/{userId}/{pageId}
  • /getPushNotification/{userId}

现在可以正常使用了。感谢所有试图提供帮助的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2021-04-13
    • 2017-12-16
    • 2017-08-20
    • 2016-11-25
    • 2015-04-04
    相关资源
    最近更新 更多