JonH
JonH

Reputation: 821

Generic Web API controller

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?

Upvotes: 6

Views: 9141

Answers (1)

JonH
JonH

Reputation: 821

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.

Upvotes: 8

Related Questions