pasluc74669
pasluc74669

Reputation: 1700

Angular 9 and .NET Web Api - How to fix CORS issue with a http.post request

i am implementing an angular 9 application, that should communicate with a .NET web api.

The web api is published in my local IIS 10 on http://localhost:8080 or http://localhost:44348 for testing when i debug from Visual Studio.

The http.get request works fine, but when I do an http.post request, i get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/api/Login/Post_User' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

but if i try to do a post request with Postman, it works fine.

This is the code I use go call the web api from my angular app:

this.apiService.post(this.user);
.....

  public post(user){
    return this.httpClient.post<any>(this.api_post_url, user).subscribe(data => {});
  }

and here is my web api method:

[HttpPost]
[ActionName("Post_User")]
public IHttpActionResult Post_User(User value)
   {
       // make insert in my database
       return Ok();
   }

... but the following "http.get" code works fine, and I am able to get my user

this.profileUserService.getByEmail(this.user.email).pipe(
            map((user: User) => {
              return user;
            })
          ).subscribe((data: User)=> {            
            if(data.name === undefined)
            {
                this.router.navigate(['/profile-user']);
            }else{
                this.router.navigate(['/profile-user']); //GO TO DASHBOARD
            }
          });        
    }

  .....

  public getByEmail(email: string){    
    this.url = `${this.api_get_url}` + email;
    return this.httpClient.get(this.url)
  }

I also tried to implement a proxy in my Angular app, but with the same result

proxy.conf.json:

{
    "/api/*": {
        "target": "http://localhost:8080",
        "secure": false,
        "logLevel": "debug"
    }
}

package.json:

...
"start": "ng serve --proxy-config proxy.conf.json",
...

and finally angular.json

...
"proxyConfig": "src/proxy.conf.json"
...

always with the same result enter image description here

Thanks in advance for your help.

Upvotes: 4

Views: 4564

Answers (1)

lucas69
lucas69

Reputation: 169

You need to enable CORS in your Web Api.

If you use .NET framework, install Microsoft.AspNet.WebApi.Cors from nuget.

Then add the following code in your WebApiConfig.cs

config.EnableCors();

Finally, add the following attribute to each methods you want

[EnanleCors(origins: "*", headers: "*", methods: "*")]

You can choose which origins can do requests

Hope this helps.

Upvotes: 2

Related Questions