Reputation: 237
I am implementing a new web application in angular 2, using an existing Web Api (ASP.NET Core), but i am having trouble with HTTP Post. After searching all kind of information, I still not abble to resolve this problem and my Web API still receiving null params from angular post.
I need to see what is wrong here. Here is my Angular 2 code:
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; }
}
Can someone tell me where Am I wrong?
Upvotes: 1
Views: 3903
Reputation: 1982
There is no reason to add JSON.stringify()
. Try removing it.
EDIT:
Either remove JSON.stringify()
or remove the braces around body data:
this.http.post('http://localhost:10832/api/Account/Register', pedido, options)
Angular will try to serialize already serialized JSON string as an object, if you leave it this way and that's why you're having an issue.
Source code: Link
Upvotes: 7