在ASP.NET Core中允许跨域资源共享(CORS)来源

7

我正在使用Microsoft.ApsNetCore.Cors 2.2

"由于CORS策略,已阻止从源'example.local'访问'exampleapi.local':
请求的资源上没有'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")]

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

4
CORS头信息需要由目标服务器设置,而不是您的服务器。 他们必须允许访问,而不是相反。 - user47589
我也遇到了与2.2完全相同的问题。 - Capo
@Christian,你有没有运气解决这个问题? - Capo
还没有,我会尝试降级到Cors,希望能解决问题。你呢?@Capo - Christian Herrejon
@ChristianHerrejon - 对于你来说,这可能是一个无从下手的问题,但我通过在我的服务器上添加以下内容最终使事情正常运行: <system.webServer> <validation validateIntegratedModeConfiguration="false" />..</system.webServer> 我也更新了我们的核心v2托管包,但似乎没有什么影响。希望这会有所帮助! - Capo
显示剩余3条评论
5个回答

3
我刚刚花了几分钟时间试图弄清楚为什么我按照官方文档设置的请求源http://localhost:8080无法使用CORS。

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

甚至Microsoft文档中都有一个注意事项!

注意:URL不能包含尾随斜杠(/)。 如果URL以/结尾,则比较返回false,并且不返回标头。


1

简便易行的方法。

  1. 安装包

Install-Package Microsoft.AspNetCore.Cors

  1. 将下面的代码放置在startup.cs文件中

app.UseCors(options => options.AllowAnyOrigin());


1

Amy在她的评论中是正确的。CORS头需要由目标服务器设置,而不是你的服务器。

如果你试图连接运行在相同IP地址上但不同端口的API(最常见的例子是localhost:<>尝试ping localhost<>等),你经常会遇到CORS的问题。

如果你想在本地机器上使用Google Chrome运行此操作,你可以下载下面的扩展程序,它将允许你切换CORS规则的开关,以便你可以在本地进行测试: 允许CORS:Access-Control-Allow-Origin


1
谢谢。如果我在本地主机上,API运行正常,但如果我在生产环境上,API会出现错误。 - Christian Herrejon

1

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

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

这个简单的添加使得所有事情神奇地为我工作。

1

这里提供的示例是: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.UseMVC 之前调用 app.UseCors。

如果您只需要来自单个来源的 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();
}

1
我尝试了两种方法,但都没有成功,不过无论如何,我很感激。 - Christian Herrejon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接