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);
}
同样,当我尝试这种方法时,会调用Post方法,但参数在框架中始终为null。但是,如果我用具有特定CommandA参数类型的Post方法替换它,它就可以工作。
我正在尝试什么?或者每个消息类型在控制器中是否需要单独的处理程序方法?
答案 0 :(得分:2)
如果您要以Json格式发送数据,那么关注博客会提供有关如何在json.net中实现层次结构反序列化的更多详细信息:
http://dotnetbyexample.blogspot.com/2012/02/json-deserialization-with-jsonnet-class.html