I have .NET core 5.0 webapi that I need to use from an Angular application, they are both running on the same machine.
The error that I get is:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: CORS request did not succeed). What have I done/tryed
- Read and try to apply other answers from SO
- Enabled CORS on the backend .NET core 5.0
- Included httpOptions on the frontend Angular
- Disabled windows firewall (is not the reason)
In the ConfigureServices I have tried :
/* attempt 1 services.AddCors(options => { options.AddDefaultPolicy( builder => { //builder.WithOrigins("http://example.com", "http://www.contoso.com"); //This is done this way to facilitate connecting frontend and backend //but this should be changed to enforce certain origins or methods builder.AllowAnyOrigin(). ; }); }); */ /* attempt 2 services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder => { builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader(); })); */ services.AddCors(c => { c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin()); }); services.AddControllers(); In the Configure method
app.UseRouting(); //app.UseCors("ApiCorsPolicy"); app.UseCors(options => options.AllowAnyOrigin()); In the Angular fronted this how I try to call a GET on the API
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class BackendService { private readonly getMovesURL = 'http://localhost:5000/api/Game/GetPossibleMoves'; private httpOptions: any; constructor(private http: HttpClient) { this.httpOptions = { observe: 'body', responseType: 'json', /* headers: new HttpHeaders({ 'Access-Control-Allow-Origin':'*' }) */ headers:{'Access-Control-Allow-Origin':'*'} }; } getGameMoves(): Observable<any> { console.log('calling: GetPossibleMoves'); return this.http.get<string[]>(this.getMovesURL, this.httpOptions); } } I have also tried withou any headers, No matter which combination I try, including answer to very similar issues here in SO. Always return these errors
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: CORS request did not succeed).

app.UseCors();at the top of yourConfigure()Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).'Access-Control-Allow-Origin'headers on your angular side. Remove that and give it a try.