9

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.