Generic Web API controller

前端 未结 1 1543
后悔当初
后悔当初 2021-01-03 04:17

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

相关标签:
1条回答
  • 2021-01-03 04:43

    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> { }
    

    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.

    0 讨论(0)
提交回复
热议问题