سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

The easiet way is to use just MVC.

You can also combine MVC + WebAPI in one site.

The reasons to go with the first option is simplicity, and learning maintaining one framework and one set of abstractions.

However if you have any of the following requirements, adding Web API becomes interesting: 1. You want to do content negotiation for response types (say XML vs. Json for the same action). 2. You want to support CORS 3. You want a help page for your API. 4. You want to structure your Url space for your API with rest and resource centric approach (basically GET /resource rather than /resource/GetData). 5. Easier to unit test controllers and actions.

Both frameworks are built by the same team, they both support attribute routing and many similar concepts, and both work well together with one another. I've seen folks take both approaches successfully. Also note that visual studio has templates that combines both of them from the get go.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top