我正在使用现有的 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/