WebAPI - CRUD业务对象的管理页面

时间:2013-11-10 17:23:19

标签: c# asp.net-web-api

在我努力创建这个之前,我想问一下:ASP.NET WebAPI是否有任何包允许一个ApiController对我的所有业务对象进行CRUD?

现在,我有一个烦人的情况,我必须创建“BookController”,“AppleController”,“LightController”等...为每个管理页面,让用户CRUD书籍,苹果和灯。

“BookController”,“LightController”等......非常相似,我不得不继续创造这些东西。

我有很多业务对象,他们不断前来,每个人都需要一个CRUD。所以这样做:

示例:

class BookController: ApiController 
{
    public HttpResponseMessage Get(int id=-1) { // do the read operation }
    public HttpResponseMessage Post(Book b) { // do the create operation }
    public HttpResponseMessage Put(Book b) { // do the update operation }
    public HttpResponseMessage Delete(Book b) { // do the delete operation }
}

对我的情况不具备可扩展性。我宁愿用这样的东西替换BookController和所有其他CRUD控制器:

class CRUDController: ApiController 
{
    public HttpResponseMessage Get(int id=-1) { // do the read operation }
    public HttpResponseMessage Post(object obj) { // do the create operation }
    public HttpResponseMessage Put(object obj) { // do the update operation }
    public HttpResponseMessage Delete(object obj) { // do the delete operation }
}

有任何建议或提示吗?

1 个答案:

答案 0 :(得分:0)

编写通用基本控制器。

class CRUDController<T> : ApiController
{
    public virtual HttpResponseMessage Get(int id=-1) { // do the read operation }
    public virtual HttpResponseMessage Post(T obj) { // do the create operation }
    public virtual HttpResponseMessage Put(T obj) { // do the update operation }
    public virtual HttpResponseMessage Delete(T obj) { // do the delete operation }
}

然后从中继承您的控制器。

class BookController : CRUDController<Book>
{
    ...
}

需要注意的一点是,如果在控制器中使用该模式,则需要注入存储库。如果没有,基本控制器内的代码将成为意大利面条。