通用Web API控制器 [英] Generic Web API controller
问题描述
我使用的Web API v2和我有,我需要为做CRUD操作模式屈指可数。例如,我有一个过敏
模式和 prescription
模式。在应用程序本身我也可以变成自己合适的车型,但为了简单起见,让我们只说我拿的型号直在Web API控制器的ViewModels。
I'm using Web API v2 and I have a handful of models that I need to do CRUD operations for. For example, I have an Allergy
model and a Prescription
model. In the application itself I have viewmodels which can turned into their appropriate models, but for simplicity's sake let's just say I take the model straight in the Web API controller.
因此,像这样:
public class PrescriptionsController
{
public HttpResponseMessage Put(Prescription model)
{
// saved to the DB
}
... (other CRUD operations)
}
我也有同样的过敏
模型:
public class AllergiesController
{
public HttpResponseMessage Put(Allergy model)
{
// saved to the DB
}
... (other CRUD operations)
}
这两种型号有不同的属性,但是否完全处理方式相同 - 其实我有大约3等车型这是每个CRUD操作的处理方式完全相同。我讨厌这样做有基本上复制和粘贴code 5种不同的端点。
Both models have different properties but are handled exactly the same way - in fact I have about 3 other models which are handled exactly the same way for each CRUD operation. I hate to do have 5 different endpoints that are basically copied and pasted code.
所以我的问题是这样的:
So my question is this:
我可以做一个通用控制器来处理所有这些模型?类似 MyCommonController< T>
? (但当然是一个更好的名字!)可以在Web API处理这种情况的路由?是,即使是一个好主意?
Can I make a generic controller to handle all of these models? Something like MyCommonController<T>
? (but with a better name of course!) Can the Web API handle the routing in that scenario? Is that even a good idea?
推荐答案
在最后我没有尝试的通用控制器。这似乎是它可能通过通过一些带有铁圈跳路由是可能的。
In the end I didn't try a generic controller. It seemed like it might be possible via jumping through some hoops with routing.
然而,事实上,路由修改得到这个工作是如此复杂,它有种否定我会得到的好处。我希望让事情变得简单。所以,我只是创建了一个通用的基类来代替:
However, the fact that routing modifications to get this to work were so complicated it kind of negated the benefit I would get. I wanted to keep things simple. So I just created a generic base class instead:
class MyBaseController<TModel> : ApiController
{
public TModel Get(int id) { ... }
}
和从它有每种类型的继承:
and had each type inherit from it:
class PrescriptionsController : MyBaseController<Prescription> { }
这工作就像魅力,并没有与路由或任何混乱。这使得它清楚发生了什么,是pretty维护。
And that worked like charm, didn't have to mess with routing or anything. It makes it clear what's happening and is pretty maintainable.
这篇关于通用Web API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!