we have an application that is built with .Net MVC. We are now tasked with exposing API's to third parties. Members on our team want to just continue down our current path and just use more controllers so we can reuse the backend of our current application. Logic tells me we need to create a seperate service layer when more clients are going to be accessing it, but .Net MVC seems to take care of all of this. Is it really acceptable architecture to use controllers in a stand alone application to expose API's and what would be the potential gains of extracting the service layer out?

migrated from stackoverflow.com Oct 25 '12 at 17:39

This question came from our site for professional and enthusiast programmers.

  • 2
    You can try ASP.NET Web API for the service layer. This post prideparrot.com/blog/archive/2012/10/asp_net_mvc_vs_webapi may help you. – VJAI Oct 25 '12 at 16:37
  • Thanks Mark, I read a little bit about that before. It includes the Controller and APIControllers all in the same project. It doesn't feel like there is any separation between the application itself and the 3rd party API's. Yet MVC 4 makes it seem as if there is. – Lizzard Oct 25 '12 at 17:12

You could use regular controllers to create an API. I would consider not mixing it with your application though and put it in a separate project/process.

Your existing controller code may be a bit too intimate with the application for it to serve as a general purpose API.

How would they "reuse the backend of our current application" if everyting is in controllers? From the new API controllers call to existing controllers? RedirectToAction? I think this will very easily fall down and you unnecessarily include infrastructure (MVC) in your model of reuse.

I think creating a service layer is a form of 'reusing the backend'. A service layer would mean extracting some bits you want to reuse. Make the service layer agnostic of MVC.

The service layer can potentially be used in desktop apps, console apps. The next gen cool web framework etc. For unit tests it can be very handy to set up test cases free of having to mock out an application framework.

  • +1 especially because mvc is harder to unittest than a thin servicelayer – k3b Sep 9 '13 at 6:54

I have seen ruby on rails applications with a rest-api that can render their content as human readable hmtl or as machine readable json or xml based on the mime type.

If Webgui and service api are quite similar you can try this, too.

If Webgui and service api are different i would not try to force the service into mvc but create a seperate thin servicelayer that wraps modell with autentification/security.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy