Angular 9 和 .NET Web Api - 如何修复 http.post 请求的 CORS 问题

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

我正在实施一个 angular 9 应用程序,它应该与 .NET 网络通信 api。

当我从 Visual Studio.

调试时,Web api 在 http://localhost:8080 or http://localhost:44348 上发布在我的本地 IIS 10 中用于测试

http.get 请求工作正常,但是当我执行 http.post 请求时,出现以下错误:

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.

但是如果我尝试用 Postman 做一个 post 请求,它工作正常。

这是我从我的 angular 应用程序调用网络 api 使用的代码:

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

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

这是我的网络 api 方法:

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

...但是下面的 "http.get" 代码工作正常,我可以得到我的用户

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

我也尝试在我的 Angular 应用程序中实现代理,但结果相同

proxy.conf.json:

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

package.json:

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

最后是 angular.json

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

总是相同的结果

在此先感谢您的帮助。

您需要在 Web 中启用 CORS Api。

如果您使用 .NET 框架,请从 nuget 安装 Microsoft.AspNet.WebApi.Cors。

然后在你的WebApiConfig.cs

中添加以下代码
config.EnableCors();

最后,将以下属性添加到您想要的每个方法中

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

您可以选择哪些来源可以做请求

希望这对您有所帮助。