gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:59:04 25 4
gpt4 key购买 nike

我正在实现一个 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"
}
}

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

最后 angular.json
...
"proxyConfig": "src/proxy.conf.json"
...

总是有相同的结果
enter image description here

在此先感谢您的帮助。

最佳答案

您需要在 Web Api 中启用 CORS。

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

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

config.EnableCors();

最后,将以下属性添加到您想要的每个方法中
[EnanleCors(origins: "*", headers: "*", methods: "*")]

您可以选择哪些源可以执行请求

希望这可以帮助。

关于Angular 9 和 .NET Web Api - 如何使用 http.post 请求修复 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61639800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com