在 ASP.NET Web API 2.0 项目中,我想使用数据模型中的 HTTP 动词GET
和类似对象进行访问,所有这些都实现了 interface 。所以我有一个基类,提供访问这些模型类的默认实现:POST
ITableRow
class ControllerBase
{
protected string whereAmI = "base controller";
public IHttpActionResult Get(int id)
{
Console.WriteLine(whereAmI + ": GET");
[... here is the default action to get the data object(s) ...]
}
public IHttpActionResult Post([FromBody] ITableRecord value)
{
Console.WriteLine(whereAmI + ": POST " + value.GetType().ToString());
[... here is the default action to create a new data object ...]
}
}
和一个想要使用ControllerBase
默认实现的派生类Post()
:
public class ElementsController : ControllerBase
{
protected string whereAmI = "element controller";
}
使用 GET 路由很容易,但是调用 POST 路由时会出现问题:
通过 Post 的 Web API 2.0 框架的自动调用现在调用该ElementsController.Post()
方法,但无法创建元素对象,因为它只知道必须将ITableRecord
对象构建为值 - 由于这只是一个接口,因此变量value
保持null
.
现在我可以在每个派生类中编写 的特定定义,从那里Post()
调用:ControllerBase.Post()
public override IHttpActionResult Post([FromBody] Element value) // this won't work since the argument types doesn't fit
{
return base.PostHelper(value); // so I have to call a helper function in base
}
我的问题是:有没有更好的(比如:更 DRY)方法来告诉派生类Post()
方法的参数必须是哪种特定类型,没有?