【问题标题】:Angular 9 and .NET Web Api - How to fix CORS issue with a http.post requestAngular 9 和 .NET Web Api - 如何使用 http.post 请求修复 CORS 问题
【发布时间】:2020-08-21 16:29:48
【问题描述】:

我正在实现一个 Angular 9 应用程序,它应该与 .NET Web api 通信。

Web api 在我的本地 IIS 10 上的 http://localhost:8080http://localhost:44348 上发布,以便在我从 Visual Studio 调试时进行测试。

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 进行发布请求,它工作正常。

这是我使用的代码 go 从我的 Angular 应用程序调用 web api:

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

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

这是我的 web 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"
...

总是得到相同的结果

提前感谢您的帮助。

【问题讨论】:

标签: angular rest api asp.net-web-api angular-services


【解决方案1】:

您需要在 Web Api 中启用 CORS。

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

然后在你的 WebApiConfig.cs 中添加以下代码

config.EnableCors();

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

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

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

希望这会有所帮助。

【讨论】:

  • 这个 WebApiConfig.cs 在哪里?
  • 我的 post 请求出现从 angular 到 asp.net web api 的 cors 错误,通过将这个启用 cors 放在我的 post 方法 cors 错误消失了。谢谢
猜你喜欢
  • 2018-07-05
  • 1970-01-01
  • 2014-01-14
  • 2020-06-21
  • 2020-01-04
  • 2021-07-02
  • 1970-01-01
  • 2019-10-03
  • 2020-07-19
相关资源
最近更新 更多