Passing JSON POST Data as an Object to a Web API Method
In ASP.NET MVC4 Web API, you may encounter a scenario where a POST request containing JSON data needs to be passed to an action method as an object. However, without proper configuration, the action method's parameter may contain null properties. To resolve this issue, you must take the following steps:
1. Specify Content-Type as "application/json":
When sending the request, ensure that the Content-Type header is set to "application/json." This informs the server that the data is in JSON format.
2. Use JSON.stringify Method:
In the client-side code, convert the JSON data to a JSON string using the JSON.stringify method. This step is crucial for the model binder to bind the JSON data to your class object.
Example:
var customer = { contact_name: "Scott", company_name: "HP" }; $.ajax({ type: "POST", data: JSON.stringify(customer), url: "api/Customer", contentType: "application/json" });
3. Decorate Action Method Parameter with [FromBody]:
In the Web API action method, decorate the parameter that will receive the JSON data with [FromBody]. This attribute indicates that the data should be bound from the request body.
Example:
public IActionResult Post([FromBody] Customer customer) { // ... }
4. Posting Complex Objects:
If your view model class contains complex properties (such as lists or nested classes), the same principles apply. Ensure that the client-side code builds an object that matches the structure of the class and sends it as JSON data with the correct Content-Type.
Troubleshooting:
The above is the detailed content of How to Pass JSON POST Data as an Object to a Web API Method in ASP.NET MVC4?. For more information, please follow other related articles on the PHP Chinese website!