ebook img

Pro ASP.NET Web API HTTP Web Services in ASP.NET PDF

604 Pages·2013·24.93 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Pro ASP.NET Web API HTTP Web Services in ASP.NET

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Contents at a Glance About the Authors ��������������������������������������������������������������������������������������������������������������xix About the Technical Reviewer �������������������������������������������������������������������������������������������xxi Acknowledgments �����������������������������������������������������������������������������������������������������������xxiii Introduction ����������������������������������������������������������������������������������������������������������������������xxv ■ Chapter 1: Introduction to ASP�NET Web API ���������������������������������������������������������������������1 ■ Chapter 2: Introduction to Asynchronous Programming in �NET �������������������������������������27 ■ Chapter 3: HTTP, REST, and Hypermedia ��������������������������������������������������������������������������57 ■ Chapter 4: HttpClient �������������������������������������������������������������������������������������������������������75 ■ Chapter 5: Sample Application: Application Structure and Domain Model ���������������������95 ■ Chapter 6: Sample Application: Building the Web API ���������������������������������������������������141 ■ Chapter 7: Sample Application: Building the Wrapper and Web Client �������������������������197 ■ Chapter 8: Routing ���������������������������������������������������������������������������������������������������������215 ■ Chapter 9: Controllers and Actions ��������������������������������������������������������������������������������231 ■ Chapter 10: Message Handlers ��������������������������������������������������������������������������������������275 ■ Chapter 11: Filters ���������������������������������������������������������������������������������������������������������289 ■ Chapter 12: Media Type Formatters and Model Binding �����������������������������������������������325 ■ Chapter 13: Input Validation ������������������������������������������������������������������������������������������365 ■ Chapter 14: Dependency Resolution ������������������������������������������������������������������������������415 ■ Chapter 15: Unit Testing and Integration Testing ����������������������������������������������������������431 v ■ Contents at a GlanCe ■ Chapter 16: Optimization and Performance ������������������������������������������������������������������463 ■ Chapter 17: Hosting �������������������������������������������������������������������������������������������������������517 ■ Chapter 18: Tracing, Logging, and API Documentation �������������������������������������������������545 Index ���������������������������������������������������������������������������������������������������������������������������������577 vi Introduction If you would like to discover the possibilities offered by HTTP on the .NET Framework, ASP.NET Web API is the technology for you. This book will get you up to speed on how it works and how to use it at both high and low levels. We have structured this book to make it really easy to use. If you would like to get your hands dirty quickly, we recommend that you work through Chapters 1 to 7 in order, because Chapters 5, 6, and 7 are all about building a sample multitier application using ASP.NET Web API. This sample application is intended as a guide on how to structure an ASP.NET Web API application in a hosting-agnostic way (from both API and client perspectives). We recommend you download the source code and run the application locally to begin with. You can download the source code from www.apress.com/9781430247258 along with all the other code related to this book. Alternatively, you can get it from GitHub (https://github.com/tugberkugurlu/PingYourPackage) through a Git client (make sure to check out the “Edition-1” branch). No matter which method you choose, be sure to read the “Run the Application” section inside the README.md file (https://github.com/tugberkugurlu/PingYourPackage/blob/Edition-1/README.md) to get the sample application running smoothly. If you prefer to get into the core of the ASP.NET Web API framework, you can choose to skip the sample application chapters and go straight to the feature-specific chapters on routing, controllers, message handlers, filters, and so on. These chapters really dive into the details of the specific parts of the ASP.NET Web API request pipeline and will give you a deep understanding of how the framework is processing your request. Required Software To use this book, you will need: • .NET Framework 4.5 or higher • Visual Studio 2012 or later • Visual Studio Extension: NuGet Package Manager • Visual Studio Extension: xUnit.net runner for Visual Studio • SQL Server Express (for sample applications and some other samples) Any other software we make use of in the book is available through NuGet. xxv Chapter 1 Introduction to ASP.NET Web API The fact that you are reading this means you are interested in learning something about ASP.NET Web API (application programming interface). Perhaps you are relatively new to web services and want an expansive view. You may already be familiar with the technology and just need to swim a bit deeper into the Web API waters; hence, you need a beacon to guide you through unfamiliar places. Or maybe you are already a pro and just want to fill those few gaps in your knowledge. Wherever you are in this journey, stay tight as we are about to start our ride, and it is going to be fun! ASP.NET Web API is the new cool kid on the block that gets us all excited. It is the new shiny tool that we love to use and it would be great to claim experience in it on our CV. But that is not why you should learn about it. We believe ASP.NET Web API is a technology that is going to change the way we think about and develop our server applications. It will change how we approach designing and implementing services. It will also affect our decisions in writing client code. ASP.NET Web API already has a rich and active community around it that is adding useful building blocks on top of its extensible model. And it is here to stay, as it talks web. So these are some of reasons why it is necessary to learn about it. This chapter won’t deal with much code, but not to worry, there will be plenty of opportunities in the upcoming chapters. But first it is essential to see how ASP.NET Web API is going to fit into the overall picture of modern web-based architecture as well as middle tier services. This chapter will start by defining what the ASP.NET Web API is and then move on to the background and architecture before giving the reasons why you would choose (or not choose) ASP.NET Web API for solving business solutions. ASP.NET Web API This section will briefly explain what ASP.NET Web API is, the libraries that comprised it, and where its source came from. We keep the more detailed discussion until after we have covered its background in the following section. The Basics ASP.NET Web API is a web framework that is built on top of Microsoft .NET 4.0 and above, implements the HTTP (HyperText Transfer Protocol) specification, and can be used to build or consume HTTP service, as opposed to SOAP (Simple Object Application Protocol) or WCF (Windows Communication Foundation) services. As we will see later, ASP.NET Web API started its life as WCF Web API, but as the team started building the framework, it became more and more evident that it was best suited as a web framework rather than a service framework. As such, the team became part of the ASP.NET team and started working with them to build the rest. The first version of the project was released in August 2012 along with Visual Studio 2012, .NET 4.5, and ASP.NET MVC (Model-View-Controller). The next version of the framework is due to be released in late 2013. 1 Chapter 1 ■ IntroduCtIon to aSp.net Web apI As Glenn Block, one of the key ASP.NET Web API project leaders puts it, ASP.NET Web API embraces HTTP as a first-class citizen and makes it extremely easy to build RESTful services. So ASP.NET Web API implements RFC 2616 (HTTP 1.1 specification) while staying nonopinionated toward REST. (REST or REpresentational State Transfer is covered as part of Chapter 3.) This was a key decision by the team, which kept ASP.NET Web API from getting entangled in the endless controversies surrounding REST and enabled it to stay practical, pragmatic, and focused on delivering value through implementing HTTP. As such, in the rest of this book we usually avoid the common phrase REST API (unless we actually mean RESTful) and instead use the phrase HTTP API. ASP.NET Web API can be used to turn a traditional ASP.NET web project into a powerful HTTP API capable of taking advantage of all the richness of HTTP including content negotiation, caching, concurrency validation, and so forth. The client part of the framework can be used by desktop or Windows phone applications (as well as server applications and middleware) to consume any HTTP API written in any framework as long as it stays compliant with the HTTP specification. ASP.NET Web API is revolutionary in many aspects not limited to the promise it delivers. It was one of the first Microsoft projects to run completely as an open source project that accepts contributions and fixes from the community. It has fully engaged with the community, constantly receiving feedback, and the team has been listening carefully to what the community has been saying. ASP.NET Web API was inspired by the ASP.NET MVC concepts and design, and it was built with similar abstractions. If you are familiar with ASP.NET MVC, you will see many parallel implementations (such as controllers, actions, filters, etc.). Yet as you will see, it improved on the modularity of its components and is an independent implementation from ASP.NET MVC and can be used on its own. ■ Note aSp.net Web apI was released with aSp.net MVC 4 and its implementation has many similarities with aSp.net MVC. a common mistake is to think of aSp.net Web apI as an extension to aSp.net MVC partly because Web apI Visual Studio templates can only be accessed by choosing an aSp.net MVC 4 project type. this notion is incorrect and unhelpful as these two frameworks are completely independent. although they can be used together, they do not have to be. aSp.net MVC is ideal for serving server-side–rendered views, while aSp.net Web apI is best used as a web service exposing a service apI. ASP.NET Web API Libraries ASP.NET Web API can be downloaded or used as NuGet packages. Also in order to get Visual Studio project templates, you need to download and install ASP.NET MVC 4. To download ASP.NET MVC 4, you can go straight to the Microsoft Download Center and look for the ASP.NET MVC 4 bundle, or you can use the Web Platform Installer and choose ASP.NET MVC 4, which will contain the essential libraries for building ASP.NET Web API as well as Web API project templates as part of the ASP.NET MVC 4 templates. If you would like to add NuGet reference to your project, depending on your scenario, you need to select from the different NuGet packages available. Each of these NuGet packages contains a subset of the framework tailored for a particular use case. It is important to note that some of these libraries are additions to the .NET Framework and are now standard DLLs (Dynamic Link Library) of .NET 4.5. Table 1-1 lists the ASP.NET Web API NuGet packages and their use cases. 2 Chapter 1 ■ IntroduCtIon to aSp.net Web apI Table 1-1. ASP.NET Web API NuGet Packages and Their Dependent Packages NuGet Package NuGet Dependency (Contains) Use Case Microsoft.AspNet.WebApi.Core Microsoft.AspNet.WebApi.Client Library development (System.Web.Http.dll) Microsoft.AspNet.WebApi.Client Microsoft.Net.Http Consuming HTTP endpoints Newtonsoft.Json using HttpClient; capable of (System.Net.Http.Formatting.dll) consuming different formats Microsoft.AspNet.WebApi.HelpPage Microsoft.AspNet.WebApi.WebHost Creating help pages for your Microsoft.AspNet.Mvc APIs implemented in ASP.NET Microsoft.AspNet.Razor Web API (templates, views, and assets required for displaying help page) Microsoft.AspNet.WebApi.OData Microsoft.Net.Http Exposing your data as an Microsoft.AspNet.WebApi.Client OData HTTP service Microsoft.AspNet.WebApi.Core Microsoft.Data.OData (System.Web.Http.OData.dll) Microsoft.AspNet.WebApi.SelfHost Microsoft.AspNet.WebApi.Core Creating a Web API service (System.Web.Http.SelfHost.dll) and exposing it inside a non-web application as a self-hosted service Microsoft.AspNet.WebApi.Tracing Microsoft.AspNet.WebApi.Core Allows the ASP.NET Web API (System.Web.Http.Tracing.dll) framework to trace to System.Diagnostics.Trace Microsoft.AspNet.WebApi.WebHost Microsoft.AspNet.WebApi.Core Hosting Web API in a web Microsoft.Web.Infrastructure application (System.Web.Http.WebHost.dll) Microsoft.Net.Http (System.Net.Http Provides a programming System.Net.Http.WebRequest) interface for modern HTTP applications; contains HttpClient Newtonsoft.Json (Newtonsoft.Json.dll) JSON serialization and deserialization One of the interesting aspects of ASP.NET Web API is that Microsoft decided to have a dependency on Newtonsoft.Json, which is an open source library. Although this had happened before with jQuery in previous versions of MVC, this is the first time Microsoft has had an open source .NET library dependency. Newtonsoft.Json is an excellent JSON (JavaScript Object Notation) implementation widely adopted in the community. Because work on the ASP.NET Web API is ongoing, there are also prerelease NuGet packages available for some of the libraries listed above. 3 Chapter 1 ■ IntroduCtIon to aSp.net Web apI ASP.NET Web API Source Code As part of the Microsoft initiative to embrace open source software (OSS), ASP.NET Web API (along with some other projects such as Entity Framework 5.0) started its life as an open source project. The project was (and is) hosted on the CodePlex web site as a Git repository and run under agile methodology with the complete visibility of the whole backlog. You can download the source code from http://aspnetwebstack.codeplex.com/SourceControl/latest. Alternatively, you can clone the Git repository hosted on the CodePlex web site. Complete instructions on how to set up Git and then clone the repository can also be found on the CodePlex web site (http://aspnetwebstack.codeplex.com/). After downloading the source code, you can run the build.cmd file in the command prompt. Before doing that, you might have to open the solution and enable the NuGet package restore on the solution so the NuGet dependencies can be downloaded. We highly recommend to download the source code, review the code, and get a feel for the extent of the framework. You can also download the nightly build libraries containing prerelease features of the ASP.NET Web API from the same web site. ASP.NET Web API Background Now that you know what ASP.NET Web API is and how to get its libraries and source code, let’s look at the context in which ASP.NET Web API was formed. As stated earlier, ASP.NET Web API is an implementation of the HTTP specification that enables you to build an HTTP API on top of the .NET Framework. Considering the HTTP 1.1 specification (which is the latest HTTP spec, although work on HTTP 2.0 has started) was ratified in 1999, why did it take 13 years for Microsoft to finally provide a first-class framework to expose the true power of HTTP? We are going to find out with a journey back in time. HTTP In the early 1990s, a few talented engineers in the CERN laboratory, led by Tim Berners-Lee, were working on a concept called the World Wide Web (originally one word, “WorldWideWeb”), which was meant to provide document exchange over the network. World Wide Web, also known as WWW or W3, was initially targeted at scientific organizations over the world to be able to author, publish, and exchange research materials. By the end of 1990, Tim Berners-Lee already had a working prototype of a web server and a browser capable of rendering documents and traversing links. In 1993, CERN decided that WWW would no longer be a proprietary body of work and it would be free for everyone to use. This led the way for an international body created by the end of 1994, which was known as the World Wide Web Consortium or W3C. W3C started to formalize the work that had been done in CERN, and as a result, drafts of a few key protocols were created. These protocols were later known as HTTP, HTML, and URI based on the earlier work by Tim Berners-Lee. These three protocols were the building blocks of the revolutionary phenomenon that we know now as the Internet. A timeline of these events is provided in Table 1-2. 4 Chapter 1 ■ IntroduCtIon to aSp.net Web apI Table 1-2. World Wide Web and HTTP Timeline Year Event 1945 Vannevar Bush described Memex, the first proto-hypertext system in the article “As We May Think.” 1960s Systems are built around the hypertext concepts such as Hypertext Editing System (HES), Project Xanadu, and oN-Line System NLS. 1970 Arthur C. Clarke predicted that satellites would someday “bring the accumulated knowledge of the world to your fingertips” using a console that would combine the functionality of the photocopier, telephone, television, and a small computer, allowing data transfer and video conferencing around the globe. 1980 Tim Berners-Lee built the first system based on hypertext. 1984 Tim Berners-Lee joined CERN to enable collaboration of scientists over the network in a heterogenous platform environment. 1989 Tim Berners-Lee wrote a proposal on a large hypertext system with typed hyperlinks. 1990 Robert Cailliau formalized Tim’s proposal and suggested the name “WorldWideWeb” or W3 for the hypertext project. 1990 Tim Berners-Lee finished building the first working prototype of a web server and a browser. 1993 Mosaic, the first graphical web browser, is built. 1993 CERN decided WWW will be free. 1994 World Wide Web Consortium is formed at MIT. 1996 HTTP 1.0 specification ratified by W3C as RFC 1945. 1999 HTTP 1.1 specification ratified by W3C as RFC 2616. 2006 Amazon uses RESTful API to expose its public cloud. 2012 Microsoft publishes ASP.NET Web API framework. Source: Wikipedia http://en.wikipedia.org/wiki/World_Wide_Web W3C published the HTTP 1.0 specification in 1996 as part of RFC 1945. This specification listed three authors: Tim Berners-Lee, Roy Fielding, and Henrik Frystyk Nielsen. By the time HTTP 1.1 was published in 1999 by the same authors (and a couple more), HTTP was not merely a document exchange protocol, it was the engine of distributed computing for many years to come. Roy Fielding, best known for proposing the REST architectural style, was seminal in bringing distributed computing concepts such as caching and concurrency to the heart of HTTP. At the time of writing HTTP 1.1 spec, he was studying toward his PhD in information and computer science, and as part of his thesis, he was working on an optimal architectural style for distributed computing. Chapter 5 of his dissertation is on REST, which was later popularized (and even idolized) by the community in the latter half of 2000. We will discuss and review REST in Chapter 3, but here it is important to note that a lot of REST is already considered (or even fulfilled) part of HTTP 1.1. 5

Description:
Pro ASP.NET Web API shows you how to build flexible, extensible web services that run seamlessly on a range of operating systems and devices, from desktops to tablets to smart phones—even the ones we don’t know today. ASP.NET Web API is a new framework designed to simplify web service architectu
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.