ASP .NET Web API in ASP .NET MVC 4 Beta
This post is part of ASP .NET MVC 4 Article Series.
With the release of ASP.NET MVC 4 beta, Microsoft shipped ASP.NET Web API within ASP.NET MVC. Developers who are familiar with WCF Web API, might know that WCF Web API is now ASP.NET Web API. However it’s a whole separate topic to discuss but here we will see how we can utilize ASP.NET Web API with ASP.NET MVC application.
Why Use ASP.NET Web API
Before ASP.NET Web API, whenever ASP.NET MVC applications requires to expose data in form of service, either for internal application usage via AJAX call or for external consumer, it return it with JSONResult from controller and it was working perfectly but with the introduction of ASP.NET Web API, it is even easier to build HTTP services around the standard HTTP method. So whenever applications require to build API services, we can put whole API implementation in separate class. By this way we can encapsulate API implementation in separate class and we can keep controller class clean and now it is only responsible to deal with view. Apart from code separation, by putting API implementation in separate class, we can also utilize below mentioned great feature of ASP.NET Web API without single line of extra code!
Full list of feature can be found here in release note. I am going to quote few of them here which I like most.
Modern HTTP programming model: we can directly access and manipulate HTTP request and response within Web API through strongly typed classes.
Full support for routes: ASP.NET Web API also support full fledged routing including route parameters, constrains.
Content negotiation: This is one of the great features which I like most. Web API will return data based on requesting client. Based on requesting client capabilities, it will choose right data format to send back to client. We will see more on this later in this post.
Model binding and validation: With model binding, we can extract data from HTTP request and can populate .NET object from it. So we can directly use that object within Web API.
Apart from above feature it also support action filter, dependency resolver, etc.
To examine ASP.NET Web API in action, let start by creating new Web API project in ASP.NET MVC 4.
Open Global.asax file and examine RegisterRoutes method. Here you will find route mapping for Web API as below. As we have seen earlier that Web API support full fledged routing.
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
One more thing if you have noticed in DefaultApi route mapping is that it is just mapping API controller name and optional parameter id. We are not mapping action as in Default route mapping. This is because as we have seen earlier that Web API is built around standard HTTP method, so it will choose and execute appropriate method from API controller based on HTTP request method (i.e. GET, POST, etc.) and optional route parameters combination. So if you are requesting API with GET method then Web API framework will look for method which start with Get… and matches route parameters with method parameters and based on these combinations, it will execute appropriate method from API controller. Web API project include one same API controller named ValuesController.cs. All API controller must derived from ApiController class. Open ValuesController.cs, here you can see implementation for HTTP Get, Post, Put and Delete method. As you can see in sample controller if we call /api/values with Get method then it is mapped to Get() and if we call /api/values/5 with Get method then it is mapped to Get(int id). This is because as we seen earlier that it will choose appropriate method based on HTTP request method and optional route parameters combination.
Content negotiation in action
As I told earlier that I am more interested in Content negotiation feature which choose return data format based on requesting client. Here we will examine it with three different scenarios.
1) Invoke /api/values with browser You should get response in XML format as displayed in below image. This is due to Accept request header as highlighted in below image.
2) Invoke /api/values with XHR Request (i.e. Ajax request) to invoke API with XHR put following JavaScript code into index.cshtml and examine request and response header in firebug or IE developer tools.
$(document).ready(function () {
$.ajax({
url: "/api/values",
success: function () {
alert('Web API Content Negotiation demo');
}
});
});
As we can see if Accept request header is */* and it is requested with XMLHttpRequest(XHR) then return type is application/json.
3) Invoke /api/values with XHR Request and datatype xml (i.e. Ajax request) to invoke API with XHR and XML as datatype put following JavaScript code into index.cshtml and examine request and response header
$(document).ready(function () {
$.ajax({
url: "/api/values",
dataType: 'xml',
success: function () {
alert('Web API Content Negotiation demo');
}
});
});
Based on above observation we can conclude following for content negotiation in Web API.
- Web API look for Accept request header and based on its value, it choose appropriate return data format.
- If Web API found Accept request header with */* then it will look for X-Requested-With header and if its value is XMLHttpRequest then it will choose JSON as a return type.
Hope this would be helpful. Stay tuned for more post on MVC4 and vNext.