首页 > 解决方案 > 在启动中启用 CORS 失败并出现预检错误

问题描述

我正在尝试在 Startup.cs 中启用 CORS,但没有成功。我在端口 4200 上有一个 Angular 应用程序,试图与我的 c# Web 应用程序通信。我在 Angular 中不断收到此错误

无法加载http://localhost:52008/Account/GetJWT:预检响应没有 HTTP ok 状态。

我的研究似乎表明 CORS 未正确启用。知道我错过了什么吗?

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
.......
 app.UseCors("EnableCORS");
 ........
 }

这是 Angular POST 请求:

  login(form: NgForm) {
    let credentials = JSON.stringify(form.value);
    console.log(credentials);
    this.http.post("http://localhost:52008/Account/GetJWT", credentials, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    })
  }

POSTMAN 查询的结果

在此处输入图像描述

标签: c#asp.netasp.net-mvc

解决方案


You could configure the cores in startup.cs like below and add the origin to ConfigurationServices like below.

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!");
    });
}

Add the CORS policy to the specific action.

[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Reference : Enable Cross-Origin Requests (CORS) in ASP.NET Core


推荐阅读