I have an ASP.NET MVC 4 application that needs to use an existing API to a different service. It is clear that ApiController’s return data and that regular Controller’s return views.
I need some form of RESTful API to interface to the external API, for Javascript functionality, but my actions (which render views) also need to call the external API. In short, both my controller actions and JavaScript-called API need to make calls to a common external API.
My question is this: How can I architect this so that my actions and the JS API make their calls with a common interface?
My two ideas so far:
- Create an
ApiControllerfor each entity. These ApiController’s then make calls to the external API. Then, my Javascipt can call these ApiController’s and in my actions, I can create an instance of each ApiController as needed and invoke their methods (GET, POST, PUT, etc.) Does this sound hackish? - Put all business logic into Model objects which then call the external API. To expose certain methods to Javascript, provide some HTTP endpoint and the Javascript passes the name of an action to invoke, which invokes Model methods which then invoke the external API.
Do either of these sounds more “correct” than the other? Or is this just another case of over-worrying and do “whatever you want”? The goal here is simply to invoke some external API in a common way that Javascript and my controller actions can access.
I would create an API controller that will serve as a bridge between your domain and the external web service. Now both your standard MVC controllers and javascript will consume this API controller. The question here is whether you could make this API controller generic so that it will avoid you the need to create an API controller per entity but use the same one. It would avoid repetition. Whether this is possible would of course depend on your exact scenario.