ASP.New Web API - 模型绑定和继承?

sma*_*dev 9 asp.net-web-api

Controller方法是否可以处理从特定基类派生的所有已发布项目?我们的想法是能够通过将命令发布到端点来调度命令.当我尝试以下操作时,Post方法中的"cmd"参数始终为null.

//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);
    }
Run Code Online (Sandbox Code Playgroud)

同样,当我尝试这种方法时,会调用Post方法,但参数在框架中始终为null.但是,如果我用具有特定CommandA参数类型的Post方法替换它,它就可以工作.

我正在尝试的是什么?或者每个消息类型在控制器中是否需要单独的处理程序方法?

Kir*_*lla 2

如果您以 Json 格式发送数据,那么以下博客提供了有关如何在 json.net 中实现层次结构反序列化的更多详细信息:

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