My First Experience with ASP.NET Web API 101
I had played with this stuff when it was still WCF Web API, but not too seriously. Then Microsoft shipped ASP.NET Web API with the beta of ASP.NET MVC 4. I finally got around to taking a look. What I found blew me away and caused me to exclaim “First ASP.NET implementation: WOW! That’s a lot easier than WCF! And that’s coming from an WCF Zealot!” Indeed, since the Indigo SDR days, I have been a WCF Zealot despite people all around having trouble with the technology and not accepting it. It’s pretty clear now, if you don’t need Interop (don’t need SOAP), you are concerned only with HTTP, and you consider that the base web technologies like GET, POST, PUT, DELETE are sufficient, there’s a far simpler way: use MVC controllers with ASP.NET Web API.
The hardships in WCF include having to explicit interfaces that define contract. WCF is all about contracts. Each method in the contract marked with the OperationContract defines an operation in the SOAP envelope of the WCF service. Finally, you must have a class that implements the service interface implementing the code and logic. The shell looks something like this:
namespace SamService { [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); [OperationContract] CompositeType GetDataUsingDataContract(CompositeType composite); // TODO: Add your service operations here } // Use a data contract as illustrated in the sample below to add composite types to service operations [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } }
namespace SamService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together. public class Service1 : IService1 { public string GetData(int value) { return string.Format("You entered: {0}", value); } public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) { throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; } } }
That’s a lot of code for the simplest service in the world! I didn’t even include the config file, because, at least in WCF 4.0, there is automatic configuration.
Now, for ASP.NET Web API, which takes the concept of a normal MVC controller and builds on it to create an experience that is simple and productive. Web API gets rid of SOAP forever and relies instead on the basics of HTTP web communication.
I worked a sample piece of code that I had in my IDE from working through the upcoming excellent book, ASP.NET MVC4 IN Action. I just needed to reference the System.Web.Http namespace and change my controller to inherit from ApiController, and then write/rewrite my Get method. Look at how much less code this takes!
using System.Web.Http; namespace GuestBook.Controllers { public class GuestbookController : ApiController { // GET api/guestbook public IEnumerable<GuestbookEntry> Get() { var mostRecentEntries = _repository.GetMostRecentEntries(); return mostRecentEntries; }
That’s it! Look at how much LESS code is needed!! Keeping things simple, you can navigate to http:[port]//api/ with IE and the Developer Tools running and you get:
You see the Response Headers:
and then the results:
If you look closely, its JavaScript Object Notation (JSON) being returned instead of WCF’s SOAP. This simpler format is understood by JavaScript making it easy for jQuery to make AJAX calls.
The last I will look at is the route that I used /api/ControllerName. ASP.NET Web API project templates define this route automatically in the global.asa file:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
In conclusion, I think for the majority of web applications (MVC apps) that don’t need to interoperate with other apps and want to simply get results back via the standard HTTP protocol, Web API is the way to go. But don’t get carried way either. A great blog post that summarized when to choose when is Matt Milner’s excellent post, “WebAPI or WCF?” As he notes,
WCF is not done, nor is it going away anytime soon. WCF is the framework to use to build services that are flexible with regard to transport, encoding, and various protocols. This was precisely what WCF was designed for and what it does extremely well. WCF enables me to write service code and contracts which can then be exposed over various bindings (transport, security, etc.). That hasn’t changed and continues to be the case. If you are building a service in your organization and plan to support multiple protocols, or simply use protocols other than HTTP (tcp, name pipes, udp, etc.) then WCF continues to be your choice.
Please read the post about the advantages of Web API in the HTTP world. Me? This WCF Zealot is still excited at how easy Web API makes working with the majority of HTTP Web applications so easy.
