Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CORS Issue with Angular 10 and net6.0 API project

From angular project when I send to GET request in my backend it works fine but if I send POST request with body that time it’s not work.

Angular Code

    login(email: string, password: string) {        
    return this.http.post<any>(`${baseUrl}/authenticate`, { email, password }, { withCredentials: true })
        .pipe(map(account => {
            this.accountSubject.next(account);
            this.startRefreshTokenTimer();
            return account;
        }));
    }

.Net Controller Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    [HttpPost("authenticate")]
    public ActionResult<AuthenticateResponse> Authenticate(AuthenticateRequest model)
    {
        var response = _accountService.Authenticate(model, ipAddress());
        setTokenCookie(response.RefreshToken);
        return Ok(response);
    }

In controller top added below flag

[ApiController]
[Route("[controller]")]
[EnableCors("AllowOrigin")]

And added cors allow code in my Program.cs

app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());

In my Browser console show this error

enter image description here

What am I missing?

>Solution :

According the documentation, You have two options to allow any origin. Use the wildcard *.
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

   builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
    {
        builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
    }));
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    
    }
    //app cors
    app.UseCors("corsapp");

OR

app.UseCors(
  options => options.WithOrigins("*").AllowAnyMethod().AllowAnyHeader()
      );

Remove this from the methods

[EnableCors("AllowOrigin")]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading