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

问题描述 投票:0回答:1

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

该web api发布在我的本地IIS 10上,在 http:/localhost:8080http:/localhost:44348。 当我从Visual Studio调试的时候,测试用的是http.get请求。

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应用中调用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"
...

殊途同归enter image description here

先谢谢你的帮助。

angular rest api asp.net-web-api angular-services
1个回答
1
投票

你需要在你的Web Api中启用CORS。

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

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

config.EnableCors();

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

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

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

希望对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.