Receiving JSON-formatted data in a Web API 2 action?

陌路散爱 提交于 2019-12-11 23:37:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!