小编Rob*_*ert的帖子

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

我在 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 …
Run Code Online (Sandbox Code Playgroud)

cors asp.net-core-mvc angular

3
推荐指数
1
解决办法
3175
查看次数

标签 统计

angular ×1

asp.net-core-mvc ×1

cors ×1