我在 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)