Passing Object as an parameter in Web Api

2019-09-06 20:08发布

问题:

In Web Api How can pass object as parameter

// GET api/values/{can be any serilizable object}
public string Get(object data)
{
    return "value";
}



   [Serializable]
    public class RequestData
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

回答1:

Your object will have to be sent in the request as JSON. [Serializable] is different kind of serialization. Here we talking either JSON or XML serialization and it is built-in

public HttpResponseMessage Get(RequestData requestData)
{
    HttpResponseMessage retMsg;
    // pack your message here, select serializer {json, xml}, etc
    return respMessage;
}



// [Serializable] - not needed, good old POCO is fine
public class RequestData
{
    public string Id { get; set; }
    public string Name { get; set; }
}