【问题标题】:Angular 2 http post null Web Api CoreAngular 2 http post null Web Api Core
【发布时间】:2017-03-29 20:51:26
【问题描述】:

我正在使用现有的 Web Api (ASP.NET Core) 在 Angular 2 中实现一个新的 Web 应用程序,但是我在使用 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();
};

视图模型:

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

}

网络 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; }
}

谁能告诉我哪里错了?

【问题讨论】:

  • 调试代码的时间:使用开发工具捕获从浏览器发送到服务器的内容并检查,您应该能够检查整个 http 请求。如果这没有帮助,请尝试使用邮递员或提琴手让它在您的客户端代码之外执行。

标签: javascript asp.net angular asp.net-web-api http-post


【解决方案1】:

没有理由添加JSON.stringify()。尝试删除它。

编辑:

要么删除JSON.stringify(),要么删除正文数据周围的大括号:

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

Angular 将尝试将已经序列化的 JSON 字符串序列化为一个对象,如果您以这种方式保留它,这就是您遇到问题的原因。

源码:Link

【讨论】:

  • angular2 文档和示例另有说明。您可以发布一些文件来支持您的声明吗?
  • 您从remove the braces around body.... 写的所有内容都是正确的。在此之前的所有内容都不准确,如果您删除它,您的答案应该可以解决 OP 的问题/问题。
  • 那是我的问题!非常感谢队友,我取下了牙套,一切正常!
  • @Igor,如果你看一下源代码link,你会看到如果Request对象的主体是Object类型,它将被JSON.stringify()序列化.自己做是没有必要的。谢谢。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 2020-10-20
  • 1970-01-01
  • 2017-08-05
  • 2015-08-14
  • 1970-01-01
相关资源
最近更新 更多