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?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.