Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Web Api controller to support any model

Tags:

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?

like image 841
DarthVader Avatar asked Aug 22 '12 16:08

DarthVader


People also ask

How do I add a model to Web API?

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.

What are controllers in Web API?

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.

Can I use MVC controller as Web API?

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.


1 Answers

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.

like image 74
Nick Albrecht Avatar answered Sep 21 '22 12:09

Nick Albrecht