2

在 ASP.NET Web API 2.0 项目中,我想使用数据模型中的 HTTP 动词GET和类似对象进行访问,所有这些都实现了 interface 。所以我有一个基类,提供访问这些模型类的默认实现:POSTITableRow

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()方法的参数必须是哪种特定类型,没有?

4

1 回答 1

2

这看起来像是仿制药的工作。首先,使您的基类泛型,并将Post方法更改为使用泛型类型。例如:

// Note the type constraint too, you may not want this depending on your use case
class ControllerBase<T> where T : ITableRecord
{
    public IHttpActionResult Post([FromBody] T value) 
    {
        //...
    }
}

现在您的派生控制器将如下所示:

public class ElementsController : ControllerBase<Element>
{
    //...
}
于 2020-12-03T11:47:58.197 回答