在.NET Core Api上启用CORS?

时间:2019-06-26 17:48:17

标签: .net-core cors

我试图让运行在localhost:4200的ANgular应用程序能够从运行在localhost:44337的后端api .NET Core 2.2 api请求数据。我在ConfigureServices中添加了Cores策略,将其添加到Configure,并在端点上添加了UseCors注释,但是仍然出现此错误:

Access to XMLHttpRequest at 'https://localhost:44337/api/users/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Startup.cs

public string DefaultCorsPolicy = "DefaultCorsPolicy";

public void ConfigureServices(IServiceCollection services) 
{
    services.AddCors(options =>
        {
            options.AddPolicy(DefaultCorsPolicy,
                builder =>
                {
                    builder
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .WithOrigins("http://localhost:4200/");
                });
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(DefaultCorsPolicy);
    app.UseMvc();
}

UsersController.cs

[HttpGet("{id}")]
[EnableCors("DefaultCorsPolicy")]
public async Task<ActionResult> GetUser(int id)
{
    var settings = await _service.GetUser(id);
    return Ok(settings);
}

如果我在实际的Response.Headers.Add("Access-Control-Allow-Origin", "*")方法中添加GetUser,它将起作用。但是我不想蛮力。

我确保将AddCorsUseCors呼叫分别放在ConfigureServicesConfigure的开头。但这仍然行不通。

1 个答案:

答案 0 :(得分:2)

这就是我的情况(与您所描述的相同)。 如果可行,您可以开始缩小范围。

services.AddCors(options =>
{
    options.AddPolicy(DefaultCorsPolicy,
        builder => builder
            .SetIsOriginAllowed((host) => true)
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
});

当然我没有[EnableCors("DefaultCorsPolicy")]属性,因为我在所有方法.AllowAnyMethod()上都允许使用该属性。