How do you properly create a Web API POST of complex object or multiple parameters using Angular2?
I have a service component in Angular2 as seen below:
public signin(inputEmail: string, inputPassword: string): Observable<Response> {
return this.http.post('/api/account/signin', JSON.stringify({ Email: inputEmail, Password: inputPassword}), this.options);
}
The targeted web api is seen below:
[HttpPost]
[Route("signin")]
public async Task<IActionResult> Signin(string email, string password)
{
....
}
This does not work because I need to convert the parameters of the web api into a single POCO class entity with Email and Password properties and put the [FromBody] attribute: Signin([FromBody] Credential credential)
Without using [FromURI]
(POST requests with query strings?), how can I make POSTs of multiple parameters or complex objects without converting these parameters into a single POCO class?
Because what if I have numerous Web API POST actions with parameters like (string sensitiveInfo1, string name, int sensitiveInfo2)
or (ClassifiedInfo info, string sensitiveInfo1, string sensitiveInfo2)
, do I need to convert them all to POCO classes and always use [FromBody]?
PS.
I was using RestangularJS
before and it can posts anything (mulitple primitive objects and complex objects) without my Web API actions having [FromBody]
attributes. Will about to investigate how RestangularJS do it.
Try this, passing a complex class object into a single data parameter.
you can receive it using a JObject in your API controller and deserialize it as according to your classes.
WebAPI does not provide this out of the box. If you try to get understanding of web API bindings, you might be able to figure out why.
I think this article might help.
WebApi will be able to deserialize your Credential object provided the JSON object has the same field names (I am not sure about case so you may be right here). You seem to be missing the headers from the post call in your Angular2 component.
Can you check the Content-Type using Chrome Debugger or Fiddler? It should be application/json.
Perhaps you should post with options:
and encode data like
If you call Web API 2.2 post method from Angular 2 type script, dont forget to add following header content and parameter object.
I have fixed the issue of Angular2 HTTP Post ASP.NET MVC Web API