Keep getting No 'Access-Control-Allow-Origin' header is present error in angular 6 with asp.net core 2.1.
I know this is the cors errors. I, have added the policy in the server side but still same issue.
startup.cs
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials().WithOrigins("http://localhost:4200");
}));
app.UseCors("CorsPolicy");
app.UseMvc();
Controller Code
[HttpPost, AllowAnonymous]
public GenericResponseObject<JwtTokenViewModel> UserAuthentication([FromBody] UserViewModel user)
{
GenericResponseObject<JwtTokenViewModel> genericResponseObject = new GenericResponseObject<JwtTokenViewModel>();
genericResponseObject.IsSuccess = false;
genericResponseObject.Message = ConstaintStingValue.TagConnectionFailed;
if (ModelState.IsValid)
{
try
{
UserViewModel userViewModel = _adminUOW.AdminAuthentication(user);
if (userViewModel != null)
{
string token = new CommonController(tokenOptions).GetToken(userViewModel, DateTime.UtcNow.AddDays(2));
genericResponseObject.Data = new JwtTokenViewModel
{
UserName = userViewModel.UserName,
UserId = userViewModel.UserId,
authenticated = true,
entityId = 1,
tokenExpires = DateTime.UtcNow.AddHours(2),
token = token,
SelectedRole = userViewModel.SelectedRole
};
}
else
{
genericResponseObject.SuccessMessage = ConstaintStingValue.Tag_No_Profile_key;
}
genericResponseObject.IsSuccess = true;
genericResponseObject.Message = ConstaintStingValue.TagConnectionSuccess;
}
catch (Exception exception)
{
genericResponseObject.IsSuccess = true;
genericResponseObject.SuccessMessage = exception.Message;
genericResponseObject.ErrorCode = exception.HResult;
genericResponseObject.ExceptionErrorMessage = exception.StackTrace;
WriteExceptionToFile.WriteExceptionToFileInLogger(_hostingEnvironment, exception);
}
}
return genericResponseObject;
}
Typescript code
login(modelValue: UserViewModel, isValid: boolean) {
if (isValid) { this.genericHttpClientService.GenericHttpPostAndResponse<GenericResponseObject<JwtTokenViewModel>, UserViewModel>(this._userViewModel, this.commonConstantValue.adminLoginUrl).subscribe(item => {
if (item.data!= null && item.data.authenticated) {
this.router.navigate(['admin-portal']);
}else{
this.genericViewModel.successMessage = item.successMessage;
}
this.progressBarDisplay = false;
},
err => {
console.log(err);
this.progressBarDisplay = false;
});
}
public GenericHttpPostAndResponse<T,TE>(postViewModel: TE, destinationUrl: string): Observable<T> {
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.httpClientModule.post<T>(environment.baseUrl + destinationUrl, postViewModel, { headers });
}
How to enable CORS in ASP.net Core WebAPI
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1