javascript - Angular 2 http post null Web Api Core

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

我正在使用现有的 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();
};

View 模型:

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

网络 API:

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

View 模型 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

关于javascript - Angular 2 http post null Web Api Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40618878/

相关文章:

javascript - 如果 HTML5 不可用,SoundManager2 能否使用 Flash 作为相同声音的备份?

javascript - Rails 中包含的默认 js

javascript - 如何更改 Angular Material 日期选择器当前日期颜色

使用 keycloak "user is not logged in"进行 Angular Testing

Angular2 RC.1 - 将路由器注入(inject)单元测试

javascript - angular 1.5 - 单向数据流 - parent 只在第一次更新子原始值,一次性?

c# - 在线设计名片应该使用pixel还是cm?

asp.net - javascript 中带有字母数字检查的文本框

asp.net - 值不能为空。参数名称 : items (DrodownList)

javascript - 用 typescript 写这个开关/案例的更好方法?