Setting up the POST Web API method?
I need to set up a Web API method to accept POST parameters sent from my Android and iOS apps. This is what I have now:
[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment([FromBody]string comment, [FromBody]string email, [FromBody]string actid)
{
string status = CommentClass.PostNewComment(comment, email, actid);
return Ok(status);
}
However, this does not work, since I believe that the method cannot take multiple [FromBody] parameters at once? How can I properly configure this method so that it takes 3 POST parameters from the request body?
+3
source to share
2 answers
You can use the model. DefaultModelBinder will bind these values ββfrom the form to your model.
public class CommentViewModel
{
public string Comment { get; set; }
public string Email { get; set; }
public string Actid { get; set; }
}
public IHttpActionResult PostComment([FromBody]CommentViewModel model)
{
string status = ...;
return Ok(status);
}
+4
source to share
You can do it -
- Create one custom class and add three properties for the three input parameters.
- Modify the method
PostComment
to accept only one parameter of this class.- When calling this WebAPI, create one object of this class, assign values ββto properties, serialize it to JSON or XML and POST.
- WebAPI will automatically de-serialize your request body and pass it to your method.
+1
source to share