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?
In Solution Explorer, right-click the Controllers folder. Select Add, then select Controller. In the Add Scaffold dialog, select "Web API 2 Controller with actions, using Entity Framework". Click Add.
Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System.
Before I illustrate how an ASP.NET MVC controller can be used as an API or a service, let's recap a few things: Web API controller implements actions that handle GET, POST, PUT and DELETE verbs. Web API framework automatically maps the incoming request to an action based on the incoming requests' HTTP verb.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With