Generic Web Api controller to support any model

asp.net-web-api, c#, generics

Solution

I did this for a small project to get something up and running to demo to a client. Once I got into specifics of business rules, validation and other considerations, I ended up having to override the CRUD methods from my base class so it didn't pan out as a long term implementation.

I ran into problems with the routing, because not everything used an ID of the same type (I was working with an existing system). Some tables had `int` primary keys, some had `strings` and others had `guids`.

I ended up having problems with that as well. In the end, while it seemed slick when I first did it, actually using it in a real world implementation proved to be a different matter and didn't put me any farther ahead at all.

Problem

Is it possible to have a generic web api that will support any model in your project? ``` class BaseApiController<T> :ApiController { private IRepository<T> _repository; // inject repository public virtual IEnumerable<T> GetAll() { return _repository.GetAll(); } public virtual T Get(int id) { return _repositry.Get(id); } public virtual void Post(T item) { _repository.Save(item); } // etc... } class FooApiController : BaseApiController<Foo> { //.. } class BarApiController : BaseApiController<Bar> { //.. } ``` Would this be a good approach? After all, i m just repeating the CRUD methods ? Can i use this base class to do the work for me? is this OK? would you do this? any better ideas?

Original source