Join Jess Chadwick for an in-depth discussion in this video Exposing data via ASP.NET Web API services, part of ASP.NET MVC 4 Essential Training.
A few videos back, we wanted to share our auction model's data access layer between our main website and our new mobile website. So, we copied the data context into a common project that they both referenced. That sounded fine at the time, but what will end up happening is that as the two sides develop independently from each other, they will inevitably end up with different logic for working with the same data. Perhaps a better option is to keep the data access within the main website and expose that data as a set of services that the mobile site or any other client for that matter is able to consume.
In this video, I'll show you how to do exactly that by creating a controller that exposes your data as a rest API using Microsoft's Web API framework. Though you can use the Web API framework to expose pretty much whatever data you like, the easiest way to get up and running with the framework is to use it to expose an entity framework data context. Luckily, we have already got one of those, so that step is complete. The next step, then, is to create the Web API controller. To do this, create a new folder in your site named Api, then right-click on the Api folder and select Add > Controller.
Name the Controller AuctionsController, but instead of creating a normal ASP.NET MVC Controller, we are going to choose the API controller with read/write actions using Entity Framework option. Then we'll choose the model that we want to expose as the data service, the Auction Model, and its associated Entity Framework DataContext, the AuctionsDataContext class. Once we have done all that, click Add to have Visual Studio generate the Controller and add it to our site.
When it's finished, take a look at what is being created. The first thing to notice is that this controller doesn't derive from ASP.NET MVC's normal Controller class, but from the API controller class, which is another kind of controller specifically designed to expose data as a rest service. Exactly what the term rest means is pretty hotly debated, but the general gist is that data is exposed via standard HTTP protocols, in other words, URLs and HTTP verbs.
With that in mind, take a look at the names of the actions in this controller, each of them contain some variation of an HTTP verb, Get, Put, Post, and Delete. Notice, too, that there are two get actions, GetAuction and GetAuctions. GetAuction takes an ID parameter and returns a single auction, whereas GetAuctions returns all of the auctions in the system. Web API is able to recognize the difference between the two and expose them via the proper URLs, for example, /api/Auctions/id for the singular version, and /api/Auctions for the plural version.
It is no coincidence that the actions in this controller match the names of HTTP verbs That's because the function that each of these actions performs is intended to match the meaning of its associated HTTP verb. For example, Delete methods delete data from a data store, Post methods create new records that are not used to update existing records, Put methods update or replace existing data, but do not create new records, and finally, Get methods get or retrieve data, in other words, Get calls are read-only and they do not ever modify data in any way.
Because they closely match standard HTTP verbs, restful interfaces are inherently compatible with pretty much anything that can make an HTTP request, making it perhaps the most universal protocol on the Internet. At this point, we are almost ready to start using our Web API controller, but since the model we are exposing is slightly complex, there is one more thing we'll need to do before this controller will work, and that is to tell Entity Framework not to generate proxy classes. Remember back when we added the Bids Collection to our Auction model and made it virtual? This is because when Entity Framework retrieves auctions from the database, it replaces this property with a proxy class that offers lazy loading, or the ability to delay loading data until it is specifically requested.
This means that when an auction is retrieved from the database, its bids are not, at least not until we specifically ask for them. Unfortunately, Web API doesn't work very well with these proxy classes. Luckily, though, it's easy to disable them. Simply add a constructor to the Web API Controller and set the DataContext Configuration.ProxyCreationEnabled flag to false. Now, to see your new Web API in action, compile and execute your site, then navigate to /api/Auctions.
Here, I'm choosing to use the Firefox browser instead of Internet Explorer because Firefox displays the XML that Web API generates and Internet Explorer does not. When we visit the api/Auctions endpoint, what we have just done is made a Get request to the Auctions collection, which returned a list of available auctions. We can also try to navigate to an individual auction using the url/api/Auctions/id. For example, api/Auctions/1, this will bring up the details of a single auction.
Unfortunately, it's not easy to make requests with other verbs using the address bar of the browser, but there are plenty of tools out there that will help you do so. It's also quite easy to make Get, Put, Post, and Delete requests to your Web API Controller in your client-side script using jQuery's Ajax Helper. Unfortunately, we'll have to end the video here, because these topics are a bit out of scope for this course. To learn more about how to make advanced HTTP requests using jQuery, check out our other web development courses here in the lynda.com online training library.
- What is Microsoft ASP.NET MVC?
- Creating your first ASP.NET MVC project
- Understanding the MVC architecture
- Interacting with models and ViewData
- Applying advanced layout techniques
- Routing requests to controller actions
- Validating user input
- Authenticating registered users
- Caching pages
- Reducing bandwidth usage with bundling and minification
- Displaying mobile-optimized content
- Simplifying a complex application with areas
- Configuring and deploying to IIS or Windows Azure