I have done a little Back-End project in dotNET 6, and now I’m starting a new Angular project. I have done all the settings, but it seems I’m missing something.
Let’s start saying this is the launchSettings.json in the dotNET project:
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:38144",
"sslPort": 44337
}
},
"profiles": {
"BackEnd_BlogDemo": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7184;http://localhost:5146",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
In the Front-End, I have the environment folder, which inside there are: environment.prod.ts and environment.ts .
Call from FrontEnd to BackEnd only works if I put the ApiURL: https://localhost:7184 , but doesn’t work if I call without the httS , at the address: http://localhost:5146, it keeps telling meabout being blocked by CORS. Why that? this is my Policy configuration on the BackEnd side, in the program.cs:
builder.Services.AddCors(options => options.AddPolicy(name: "MyPolicy",
policy =>
{
policy.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
}));
And then:
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseCors("MyPolicy");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is the CORS Policy error I get:
Just for the info, this is the authservice in Angular:
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {
}
type: string = 'api/Auth';
register(registerDTO: RegisterDTO): Observable<ServiceResponse<boolean>> {
return this.http.post<ServiceResponse<boolean>>(environment.APIEndpoint + this.type + '/Register', registerDTO);
}
}
And this is the environment.ts folder (the environment.prod.ts it’s the same but just it’s on production = false):
export const environment = {
production: true,
APIEndpoint: "http://localhost:5146/"
};
2
Answers
try adding
Access-Control-Allow-Origin
header to your api in your controller. for example:If you edit your code in this way, I think you will not have any errors.