【问题标题】:Allow Cors Origin in ASP.NET Core在 ASP.NET Core 中允许 Cors Origin
【发布时间】:2021-05-11 00:58:51
【问题描述】:

我正在使用 Microsoft.ApsNetCore.Cors 2.2

“从源 'example.local' 访问 'exampleapi.local' 的 XMLHttpRequest 已被 CORS 策略阻止:
请求的资源上不存在“Access-Control-Allow-Origin”标头。”

我用这个设置设置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
                builder =>
                {
                    builder                            
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
    });

    services.Configure<TokenSettings>(this.Configuration.GetSection("Tokens"));
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(opt =>
        {
            opt.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Tokens:Issuer"],
                ValidAudience = Configuration["Tokens:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Tokens:SecurityKey"]))
            };
        });

    services.AddMvc();
    services.Configure<LdapConfig>(Configuration.GetSection("ldap"));
    services.AddScoped<ILdapAuthenticationService, LdapAuthenticationService>();
    services.AddScoped<IUserService, UserService>();
    services.AddScoped<IProjectService, ProjectService>();
    services.AddScoped<IProjectMembersService, ProjectMembersService>();
    services.AddScoped<IJourneyUsersService, JourneyUsersService>();
    services.AddScoped<IProjectRolesService, ProjectRolesService>();
    services.AddScoped<IPmoGuardianService, PmoGuardianService>();
    services.AddScoped<IHolidaysService, HolidaysService>();
    services.AddScoped<IMailService, MailService>();
    services.AddScoped<INotificationsService, NotificationsService>();
    services.AddScoped<INotificationUsersService, NotificationUsersService>();
    services.Configure<AWSConfigSes>(Configuration.GetSection("AWSSmtp"));
    services.AddDbContext<JourneyContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("JourneyConnection")));
    services.AddDbContext<TSMContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("TSMConnection")));
    services.AddDbContext<PmoGuardianContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("PmoGuardianConnection")));

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMailService mail, INotificationsService not)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    Recurrence recurrency = Recurrence.GetInstance(not);
    //new TSMClockService(mail);

    app.UseCors("AllowSpecificOrigin");
    app.UseAuthentication();

    app.UseMvc();
}

[Produces("application/json")]
[Route("api/Mail")]
[EnableCors("AllowSpecificOrigin")]

但它不起作用,总是我得到同样的错误

【问题讨论】:

  • CORS 标头必须由目标服务器设置,而不是 您的 服务器。 他们必须给访问权限,而不是相反。
  • 我在 2.2 中遇到了完全相同的问题
  • @Christian 你有运气解决这个问题吗?
  • 还没有,我会尝试降级到 Cors,我希望能解决这个问题。和你?? @Capo
  • @ChristianHerrejon - 这对你来说可能是在黑暗中拍摄,但我终于能够通过添加 .. 到我服务器上的 webconfig。我也更新了我们的核心 v2 托管包,但这似乎没有效果。希望这会有所帮助!

标签: c# asp.net-web-api asp.net-core


【解决方案1】:

我刚刚浪费了几分钟试图弄清楚为什么 CORS 不能处理我根据官方文档设置的来自 http://localhost:8080 的请求。

这是因为我在 URL 的末尾添加了一个“/”。因此,请从允许的来源中删除您的“/”。

甚至在 Microsoft 文档中也有关于此的注释!

注意:URL 不能包含尾部斜杠 (/)。如果网址 以 / 结束,比较返回 false 并且没有标题 返回。

【讨论】:

    【解决方案2】:

    艾米的评论是对的。 CORS 标头需要由目标服务器设置,而不是您的。

    如果您尝试挂接到不同端口上的 API 但在同一 IP 地址上本地运行(最常见的示例是 localhost: 尝试 ping localhost 等,则通常会发现 CORS 存在问题。 )。

    如果您尝试使用 Google chrome 在本地计算机上运行此程序,您可以下载以下扩展程序,该扩展程序允许您打开和关闭 CORS 规则,以便您可以在本地进行测试: Allow CORS: Access-Control-Allow-Origin

    【讨论】:

    • 谢谢。如果我在本地主机上,API 工作正常,但如果我在生产环境中,API 会收到错误
    【解决方案3】:

    这是这里提供的例子:ASP.NET Core 2.2

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://example.com"));
            });
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
            ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            // Shows UseCors with named policy.
            app.UseCors("AllowSpecificOrigin");
    
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    

    最后在控制器或动作上这样使用:

    [EnableCors("AllowSpecificOrigin")]
    

    另外,由于某种原因,请确保 app.UseCors 在 app.UseMVC 之前被调用。

    此外,如果您只需要来自单一来源的 CORS;您使用没有策略的更简单的解决方案:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseCors(
            options => options.WithOrigins("http://example.com").AllowAnyMethod()
        );
    
        app.UseMvc();
    }
    

    【讨论】:

    • 两个都试过了,还是不行,还是很感激
    【解决方案4】:

    简单易行的方法。

    1. 安装包

    Install-Package Microsoft.AspNetCore.Cors

    1. 将下面的代码放入startup.cs文件

    app.UseCors(options =&gt; options.AllowAnyOrigin());

    【讨论】:

      【解决方案5】:

      我知道这是一个老问题,但如果您像我一样使用 appsettings.json 文件进行配置,请务必添加以下内容:

      "cors": {
        "rules": [
          {
            "origin": "https://localhost:44379",
            "allow": true
          }
        ]
      }
      

      这个简单的添加让一切都为我神​​奇地工作。

      【讨论】:

        猜你喜欢
        • 2019-08-19
        • 2020-12-06
        • 1970-01-01
        • 2022-09-28
        • 2021-10-23
        • 2018-07-05
        • 2013-12-09
        • 2017-03-22
        • 2019-07-02
        相关资源
        最近更新 更多