【发布时间】:2021-02-07 19:56:41
【问题描述】:
我正在尝试从 Angular 8 访问 .Net 核心 WebApi,我可以使用 HttpGet 方法,但使用 post 方法,同时将寄存器数据作为对象传递是不允许的。显示 400 问题。下面是为命中而编写的代码。请帮忙。 RegisterCompoent.ts.
this.userService.RegisterUser(this.userForm.value).subscribe((data) => {
if (data) {
alert("Registration successfull, go ahead and login");
this.router.navigate(['']);
}
}, error => this.errormessage = error)
}```
UserService.ts
```httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
RegisterUser(userDetails: any ):Observable<UserInfo> {
// return this.http.post<UserInfo>('https://localhost:44322/api/User/RegisterUser/',userDetails,this.httpOptions)
return this.http.post<UserInfo>('https://localhost:44322/api/User/RegisterUser/',JSON.stringify(userDetails),this.httpOptions)
}```
.Net Core WebAPI RegisterUser
```[ApiController]
[Route("api/User/[Action]")]
public class UserController : ControllerBase
{
SqlRepository repository = new SqlRepository();
[HttpPost]
public int RegisterUser(UserInfo userInfo)
{
return repository.RegisterUsers(userInfo);
}
//[HttpPost]
//public int RegisterUser([FromBody] string userInfo)
//{
// UserInfo userDetails = JsonConvert.DeserializeObject<UserInfo>(userInfo.ToString());
// return repository.RegisterUsers(userDetails);
//}```
please help the error it shows
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/vvTts.png
【问题讨论】:
-
尝试删除您的“JSON.stringify”。您不需要这个,并且您可能会将对象更改为扁平字符串。 angular.io/guide/http#making-a-post-request
-
吉尔斯达夫有同样的错误。 ``` RegisterUser(userDetails: UserInfo):Observable
{ // return this.http.post ('localhost:44322/api/User/RegisterUser/…) return this.http.post ('localhost:44322/api/User/RegisterUser/…) }`` `我错过了什么 -
我想知道它是如何获取表单的数据以及数据的格式。通过这样的方法,RegisterUser(userDetails: any) 无法知道数据的具体格式。
标签: angular asp.net-core-webapi