2

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;
            });

    }

error detailsHttpCLient

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 });
}

Getting Error " No 'Access-Control-Allow-Origin' header is present on the requested resource." in ionic2

How to enable CORS in ASP.net Core WebAPI

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1

San Jaisy
  • 15,327
  • 34
  • 171
  • 290

1 Answers1

0

Hard to say what the real problem is. My experience with CORS is that it is harder in practice than one would think. I had a similar problem, which was due to my site requiring Windows Authentication. Turns out that the preflight CORS request requires anonymous authentication. I see that your controller has AllowAnonymous attribute, but, if this is hosted in i.e. IIS, then the site needs to have anonymous authenticationt too.

Spiralis
  • 3,232
  • 2
  • 39
  • 53