问题
I'm working on a RESTful API using JSON for the input and output - requests coming in should have JSON formatted bodies containing relevant data and the response will similarly be JSON formatted.
The problem I'm having is that I can't for the life of me figure out how to collect the information from the POST request and have it properly mapped to the relevant objects.
For example, I want to allow POST requests for "/contacts" which will contain a JSON formatted Contact object similar to this:
{"Given":"John", "Surname":"Doe"}
The problem is, no matter what I try I can't get the receiving action to recognise this information. How do I access the JSON object submitted in the request body, within my action?
[RoutePrefix("contacts")]
public class ContactsController : BaseController
{
[Route("")]
[ResponseType(typeof(ApiResponse))]
public IHttpActionResult PostContacts(FormDataCollection data)
{
ApiResponse response = new ApiResponse();
response.Data = data;
return Ok(response);
}
}
The response always contains a null value for "response.Data" and when I debug the application I can see that "data" is in fact null.
Edit:
I forgot to mention how I'd like this to work. Ideally I want my action to have a signature similar to this:
public IHttpActionResult PostContacts(Contact contact) {}
Where the contact variable is populated automatically based off the JSON included in the incoming request body.
回答1:
If your Contact
class has same property names as in JSON object,
publc class Contact {
public string Given { get; set; }
public string Surname{ get; set; }
}
then Web API will bind the object for you
public IHttpActionResult PostContacts(Contact data)
{
ApiResponse response = new ApiResponse();
response.Data = data;
return Ok(response);
}
Still if it is not working, you might need to show how you are posting your data.
回答2:
Try loading the object from the body like this:
public IHttpActionResult PostContacts([FromBody]Contact contact) {}
This should automatically populate your Contact
object if your properties on the json object are named appropriately. That way you won't have to use the FormDataCollection at all.
来源:https://stackoverflow.com/questions/24155504/receiving-json-formatted-data-in-a-web-api-2-action