Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.New Web API - Model Binding and Inheritance?

Is it possible for a Controller method to handle all Posted items which derive from a particular base class? The idea is to be able to dispatch Commands by posting them to an endpoint. When I try the following, the "cmd" parameter in the Post method is always null.

Example

//the model:
public abstract class Command{
    public int CommandId{get; set;}
}
public class CommandA:Command{
    public string StringParam{get; set;}
}
public class CommandB:Command{
    public DateTime DateParam{get; set;}
}

//and in the controller:
    public HttpResponseMessage Post([FromBody]Command cmd)
    {
        //cmd parameter is always null when I Post a CommandA or CommandB
        //it works if I have separate Post methods for each Command type
        if (ModelState.IsValid)
        {
            if (cmd is CommandA)
            {
                var cmdA = (CommandA)cmd; 
                // do whatever
            }
            if (cmd is CommandB)
            {
                var cmdB = (CommandB)cmd;
                //do whatever
            }

            //placeholder return stuff
            var response = Request.CreateResponse(HttpStatusCode.Created);
            var relativePath = "/api/ToDo/" + cmd.TestId.ToString();
            response.Headers.Location = new Uri(Request.RequestUri, relativePath);
            return response;
        }
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

Again, when I try this approach the Post method gets called, but the parameter is always null from the framework. However if I replace it with a Post method with a specific CommandA parameter type, it works.

Is what I'm attempting possible? Or does every message type need a separate handler method in the controller?

like image 862
smalltowndev Avatar asked Sep 03 '12 18:09

smalltowndev


1 Answers

If you are sending data in Json format, then following blog gives more details about how hierarchies deserialization can be achieved in json.net:

http://dotnetbyexample.blogspot.com/2012/02/json-deserialization-with-jsonnet-class.html

like image 189
Kiran Avatar answered Sep 24 '22 15:09

Kiran