Search code examples
asp.net-mvcrazorasp.net-mvc-viewsasp.net-apicontroller

Create a View against an API controller?


I need to create a website where some of it's pages should be accessible from external clients via an API, but I still want to make regular MVC Razor views to retrieve, display and manipulate the same data.

What's the best way to achieve this?

Update

What the API will have to expose is just data manipulation.

For the web pages, I still want to benefit from the razor chtml views, I prefer not polluting my views with redundant jQ or JS nor data- attributes that consume the data.


Solution

  • Just create an MVC project with the pages you want, and then create ApiControllers (from the Web API framework) to serve as RESTful endpoints. You can program your views to retrieve data from the API actions as JSON objects, and consume them with javascript. Other people can hit the same API actions and use the data in some other way.

    If you want to start with a WebApi, and build basic views based on the same data that someone else could access via that API, you could inject your WebApi controllers into your normal MVC controllers, and invoke their methods to get the data that you need to build your ViewModels. This should work all right as long as your API controllers don't need to do anything "outside the box" like inspecting the Request object directly.

    A more robust method would be to create a "Manager" layer that handles all the business logic of your application, and then have your ApiControllers be nothing but thin wrappers around calls to their respective Manager classes. This would add a little maintenance cost, but it would adhere to the Single Responsibility Principle a little better.