Angular 2 http post null Web Api Core

Angular 2 http post null Web Api Core

本文关键字:Web Api Core null post http Angular      更新时间:2023-09-26

我正在angular 2中实现一个新的web应用程序,使用现有的web Api (ASP. js)。. NET核心),但我有麻烦与HTTP Post。在搜索了各种信息之后,我仍然无法解决这个问题,我的Web API仍然从angular post接收空参数。

我要看看这里出了什么问题。下面是我的Angular 2代码:

   posted(event) {
 @Injectable()
export class httpTestComponent {
constructor(public http: Http) {
};
posted(event) {
    var user: UserViewModel = {
        name: "angularUser",
        password: "pw",
        email: "angularMail"
    }
    let pedido = JSON.stringify(user);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    this.http.post('http://localhost:10832/api/Account/Register', { pedido }, options)
        .map(this.extractData).catch(this.handleError).subscribe();
};

ViewModel:

export interface UserViewModel {
name: string,
password: string,
email: string,

}

Web API:

 [HttpPost]
    [Route("Register")]
    public void Register([FromBody] UserRegisterViewModel userVm)
    {
   }

ViewModel WEB API:

    public class UserRegisterViewModel
{
    public string name { get; set; }
    public string password { get; set; }
    public string email { get; set; }
}

谁能告诉我我错在哪里?

不需要添加JSON.stringify()。试着把它去掉

编辑:

删除JSON.stringify()或删除体数据周围的大括号:

this.http.post('http://localhost:10832/api/Account/Register', pedido, options)

Angular会尝试将已经序列化的JSON字符串序列化为对象,如果你不这么做,这就是问题所在。

源代码:Link