To force Web API to read a simple type from the request body, add the [FromBody]
attribute to the parameter:
public class Person { public string FirstName { get; set; } public string LastName { get; set; } }
[Route("hello2"), HttpPost] public JsonResult Hello2([FromBody] Person person) { string output = $@"Hello {person.FirstName} {person.LastName}"; return Json(output); }
When a parameter has [FromBody]
, Web API uses the Content-Type header to select a formatter. In this example, the content type is “application/json” and the request body is a raw JSON string (not a JSON object).