Http.Post将参数传递为null

时间:2018-05-31 05:42:51

标签: asp.net asp.net-mvc angular asp.net-web-api

我一直在尝试将一个类对象从angular 6 service post调用传递给web api post方法,api方法成功命中,但我传递的类对象显示为null。

AngularJS服务: -

  import { Injectable } from '@angular/core';
  import { User } from './user.model'
  import { Http, Response, Headers, RequestOptions, RequestMethod } from 
  '@angular/http';
  import { Observable } from 'rxjs/Observable' ;
  import 'rxjs/add/operator/map';
  import 'rxjs/add/operator/toPromise';

  @Injectable({
  providedIn: 'root'
  })
  export class UserService {
  selectedUser: User;
  constructor(private http: Http) { }
  postUser(user: User) {
  debugger;
  var body = JSON.stringify(user);
  var headerOperations = new Headers({ 'Content-Type': 'application/json' 
  });
  var requestOptions = new RequestOptions({ method: RequestMethod.Post, 
  headers: headerOperations })
  return this.http.post('http://localhost:54516/Account/Register', body, 
  requestOptions).map(x => x.json);
  }
  }

Web API方法:

[AllowAnonymous]       
[HttpPost]
//[ValidateAntiForgeryToken]
public void Register(User body)
{
}

模特课程:

public class User
    {       
    public string Email { get; set; }

    public string PhoneNumber { get; set; }

    public string Password { get; set; }

    public string ConfirmPassword { get; set; }
}

以下是AngularJs Side的行动数据:

enter image description here

最后,使用null对象的Web Api Controller方法:

enter image description here

Cors已经在控制器上自行定义。

[EnableCors(origins: "http://localhost:4200",headers:"*", methods:"*")]

2 个答案:

答案 0 :(得分:1)

首先,您不需要<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> </head> <body> <table> <tr><td>Hello</td></tr> <tr><td>Hello</td></tr> <tr><td>Hello</td></tr> <tr><td>Hello</td></tr> <tr><td>Maniac</td></tr> <tr><td>Hello</td></tr> </table> <button>button1</button> <button>button2</button> <script> $('table').find('tr:gt(2)').hide(); $("button").on("click", function() { $('table').find('tr:gt(2)').toggle(); }); </script> </body> </html> 身体,您可以删除此行

stringify

并尝试将var body = JSON.stringify(user); 属性添加到操作的参数

[FromBody]

答案 1 :(得分:0)

试试这个:

 postUser(user: User) {
        let bodyString = JSON.stringify(user);
        let headers = new HttpHeaders({ 'Content-Type': 'application/JSON' });
        return this._http.post<any>('http://localhost:54516/Account/Register', bodyString, { headers: headers });
    }

并在服务器中:

[AllowAnonymous]       
 [HttpPost]
 //[ValidateAntiForgeryToken]
 public void Register([FromBody]User body)
 {

 }