Angular 9 和 .NET Core - 从源 localhost:4200 访问已被 CORS 策略阻止

Rob*_*ert 3 cors asp.net-core-mvc angular

我在 Angular 9 中有应用程序,在 .NET Core 3.1 中有后端当我想从 Angular 客户端发出请求时:

private httpHeaders: HttpHeaders;

  constructor(private httpClient: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
    this.httpHeaders = new HttpHeaders({
      'Access-Control-Allow-Origin': '*' 
  });
  }

 return this.httpClient.get<any>(`${environment.apiUrl}/findUser/GetUsers?name=${name}&lastname=${lastname}`, {
        headers: this.httpHeaders,
      reportProgress: true,
      observe: 'events'
    });
Run Code Online (Sandbox Code Playgroud)

Startup.cs我的设置中看起来像这样:

services.AddCors();
 services.AddControllers();

app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
Run Code Online (Sandbox Code Playgroud)

在控制器中:

[HttpGet]
[Route("getUsers")]
public IEnumerable<UserAccountDTO> GetUsers(string name, string lastname)
{}
Run Code Online (Sandbox Code Playgroud)

但它不起作用:

  Access to XMLHttpRequest at 'http://localhost:20677/findUser/GetUsers?
name=&lastname=John' from origin 'http://localhost:4200' has been blocked by CORS
 policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

这是请求:

GET /findUser/GetUsers?name=&lastname= HTTP/1.1
Host: localhost:20677
Connection: keep-alive
Access-Control-Allow-Origin: *
Accept: application/json
Authorization: Bearer xxxxxxxxxxxxxxx
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36
Content-Type: application/json
Origin: http://localhost:4200
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:4200/find-user
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Run Code Online (Sandbox Code Playgroud)

Eli*_*seo 7

我认为是,请参阅文档

// in ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(
            name: "AllowOrigin",
            builder =>{
                builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
            });
    });
}

// in Configure
public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowOrigin");
}
Run Code Online (Sandbox Code Playgroud)

注意:我在收到 ok 后更新了答案;我错过了 UseCors 中的双引号。


2021 年 4 月 17 日更新

app.UseCors("AllowOrigin"); 必须位于其他中间件的顶部。