6

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.

So something like this:

  public class PrescriptionsController
  {
        public HttpResponseMessage Put(Prescription model)
        {
              // saved to the DB
        }

        ... (other CRUD operations)
  }

I also have the same for the Allergy model:

  public class AllergiesController
  {
        public HttpResponseMessage Put(Allergy model)
        {
              // saved to the DB
        }

        ... (other CRUD operations)
  }

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:

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
JonH
  • 821
  • 11
  • 19
  • I think you can achieve this in different way .. by routing. I haven't tried, but will see. – Guanxi Apr 11 '14 at 23:43
  • Seems possible. Here's a discussion about it: http://stackoverflow.com/questions/12077361/generic-webapi-controller – Trisk Apr 12 '14 at 15:36

1 Answers1

8

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.

JonH
  • 821
  • 11
  • 19
  • john , could you post some code. I have tried this approach and was unsuccessful. I have read articles that speak to this approach not working because of the way webApi discovers controllers. I have largely abandoned the effort because the savings simply were getting lost in the amount of time it took me to research – greg May 16 '22 at 14:26