Introduction

“I hear...I forget, I see...and I remember, I do...and I understand”

—Confucius

The Hypertext Transfer Protocol (HTTP) is the application-level protocol that powers the World Wide Web. One of the greatest characteristics of HTTP is that it finds support in multiple platforms. HTTP is the lowest common denominator of many platforms and devices. Hence, the primary benefit of creating an HTTP-based service is reachability. A broad range of clients in disparate platforms can consume your HTTP services.

ASP.NET Web API is a framework from Microsoft for building HTTP services. It is not the only possible means for building HTTP services in the .NET technology stack; there is Windows Communication Foundation (WCF) as well, but the ASP.NET Web API framework embraces HTTP instead of fighting against it or abstracting it away. ASP.NET Web API enables you to create HTTP services through the powerful ASP.NET MVC programming model of preferring convention over configuration, which is familiar to many .NET web developers. Some of the best features from ASP. NET MVC, such as routing, model binding, and validation, are all part of ASP.NET Web API as well. ASP.NET Web API also lends itself well to unit testing, in a similar way toASP.NET MVC.

This book, Practical ASP.NET Web API, is a practical guide that will help you master the basics of the great ASP.NET Web API framework in a hands-on way. It takes a code-centric approach that will help you grasp the concepts by seeing them in action as you code, run, and debug the projects that you create as you follow the exercises of a chapter.

Though the main focus of the book is the practice, which is the ‘how’ part of ASP.NET Web API framework development, the ‘what’ and ‘why’ parts are implicitly covered to the extent needed for you to understand and appreciate the underlying theoretical concepts demonstrated by the practical code, as you work through the various scenarios. You will see a lot of code, covering all the practical and basic scenarios that are commonly encountered by developers. The recommended approach that will provide the maximum benefit is to follow this book’s exercises in sequence and code-along. Although it is a bit of work, I recommend you manually type the code instead of copying and pasting it from the book’s download files into the Visual Studio classes you work on. This will help you grasp what you are trying to do, as you work through an exercise. However, if having the completed source code by your side will be of help, you can find the code for the examples shown in this book on the Apress web site, www.apress.com. A link can be found on the book’s information page under the Source Code/Downloads tab.

If you are looking for a book to just read through and gain an understanding of the ASP.NET Web API framework by simply looking at code listings, this is mostly not your book. While you will see lots of code, this is not a recipe book. Though you will find the code listings in the book useful and relevant for many of the scenarios you face day-to-day, the intention of this book is not to provide you ready-made code that you can copy and paste into the code you are working on in a real-life project and forge ahead. The objective instead is to provide you the hands-on experience of learning the basics of the ASP.NET Web API framework. In short, this book follows the proverb quoted in the epigraph—do, and you will understand.

What You’ll Learn

  • The basics of HTTP services and debugging through Fiddler.
  • Request binding and validation.
  • Response formatting and customization to suit client preferences.
  • Managing the controller dependencies and unit testing.
  • Hosting and security fundamentals.
  • Consuming HTTP services from various clients.
  • Building a performant web API.

How This Book is Organized

Practical ASP.NET Web API is organized into twelve chapters built around hands-on exercises. Each exercise builds on the previous one and for this reason, I highly recommend not only reading the chapters in order but also following the exercises within a chapter in the order presented. You’ll find the following chapters in this book.

Chapter 1: Building a Basic Web API

We start off by understanding the differences in building HTTP services using Windows Communication Foundation (WCF) versus ASP.NET Web API at a high level and move on to building our first service, which exposes an in-memory collection over HTTP. We then look at overriding the default behavior of the ASP.NET Web API framework in selecting the action methods based on the HTTP method and finish off the chapter by creating a create-read-update-delete service that plays by the rules of HTTP.

Chapter 2: Debugging and Tracing

The ability to view HTTP traffic, which consists of the request message sent by the client and the response message sent by ASP.NET Web API in response to the request, and the ability to hand-craft requests and submit the same to ASP.NET Web API to view the corresponding response are fundamental requirements for building HTTP services. This chapter covers Fiddler, a great tool for HTTP debugging, and the web browsers’ built-in tools to capture and inspect the HTTP traffic. This chapter also covers the tracing feature that comes with the ASP.NET Web API framework.

Chapter 3: Media-Type Formatting CLR Objects

This chapter introduces you to the concept of formatting, which is introduced in the ASP.NET Web API framework. You will understand how the process of content negotiation (conneg) works and learn to override and extend it. You will create media type mappings through a query string and request header, a custom media type mapping, and a custom media formatter, and you’ll learn to extend the out-of-box JSON media formatter. Finally, you’ll look at controlling what and how members of a type get serialized into HTTP response.

Chapter 4: Customizing Response

Content negotiation is not just about choosing the media type for the resource representation in the response. It is also about the language, character set, and encoding. In Chapter 3, content negotiation is covered from the media type perspective. This chapter explores content negotiation from the perspective of language, character set, and content encoding.

Chapter 5: Binding an HTTP Request into CLR Objects

This chapter introduces the concept of binding, which is borrowed from the ASP.NET MVC framework. Binding in ASP.NET Web API is much broader, with media type formatters also having a role to play. You will learn the three types of binding: model binding, formatter binding, and parameter binding; and you’ll learn how to extend the framework by creating custom value providers, custom model binders, custom parameter binders, and custom media-formatters.

Chapter 6: Validating Requests

This chapter covers model validation, a process that is part of model binding, by which ASP.NET Web API runs the validation rules you set against the properties of your model classes. You will use the out-of-box data annotations to enforce the validity of the incoming request and handle the errors raised by model validation. You will also extend the out-of-box validation attribute, create your own validation attribute, and create a validatable object.

Chapter 7: Managing Controller Dependencies

This chapter covers the techniques related to managing one of the most common dependencies an ASP.NET Web API controller takes, which is the dependency on the classes related to persistence infrastructure such as a database. You start off building a controller that depends on Entity Framework and move on to invert the dependencies using the interfaces part of Entity Framework; this is followed by applying the repository pattern and generalizing that pattern into a generic repository. You will also look at mapping domain objects to data transfer objects (DTO) using AutoMapper, injecting dependencies using StructureMap, and writing automated unit tests against the controller by using RhinoMocks as the mocking framework.

Chapter 8: Extending the Pipeline

ASP.NET Web API is a framework. You don’t call the framework code but it calls your code, in line with the Hollywood principle. The most fundamental lever that you use to harness the power of ASP.NET Web API framework is the controller, the ApiController subclass that you write. In addition, the ASP.NET Web API framework has various points of extensibility built in, for us to hook our code in and extend the processing. This chapter covers the extensibility points of message handlers, filters, and controller selectors.

Chapter 9: Hosting ASP.NET Web API

Though ASP.NET Web API includes ASP.NET in its name, it is not tied to the ASP.NET infrastructure. In fact, ASP.NET Web API is host-independent. This chapter covers the three ways you can host your HTTP services built using ASP.NET Web API: (1) using the ASP.NET infrastructure backed by Internet Information Services (IIS), called web hosting, (2) using any Windows process such as a console application, called self-hosting, and (3) connecting client to the web API runtime, without hitting the network, called in-memory hosting and used mainly for testing purposes.

Chapter 10: Securing ASP.NET Web API

Authentication and authorization are the fundamental building blocks to secure any application, including ASP.NET Web API-powered HTTP services. This chapter covers HTTP basic authentication as an example for implementing the direct authentication pattern and a client obtaining a JSON Web Token (JWT) from an issuing authority and presenting the same to ASP.NET Web API as an example for brokered authentication pattern. This chapter also covers authorization based on roles implemented using Authorize filter.

Chapter 11: Consuming ASP.NET Web API

One of the greatest benefits of building HTTP services is the reachability. A broad range of clients in disparate platforms can consume your HTTP service, leveraging the support HTTP enjoys across the platforms and devices. This chapter covers the topic of the client applications consuming your ASP.NET Web API. The coverage is limited to two .NET clients: a console application and a Windows Presentation Foundation (WPF) application, and a JavaScript client running in the context of a browser.

Chapter 12: Building a Performant Web API

Performance, an indication of the responsiveness of an application, can be measured in terms of latency or throughput. Latency is the time taken by an application to respond to an event, while throughput is the number of events that take place in a specified duration of time. Another quality attribute that is often used interchangeably is scalability, which is the ability of an application to handle increased usage load without any (or appreciable) degradation in performance. The topics of performance and scalability are vast and hence this chapter focuses on a few select areas in ASP.NET Web API, namely asynchronous action methods, pushing real-time updates to the client, and web caching.

What You Need to Use This Book

All the code listing and the samples in this book are developed using Visual Studio 2012 Ultimate Edition, targeting the .NET framework 4.5 in Windows 7 and hence Visual Studio 2012 is a must to use this book. Since ASP.NET Web API is a part of ASP.NET MVC 4.0 and it ships with Visual Studio 2012, you will not need any separate installs to get the ASP.NET Web API framework.

For the exercises that involve creating automated unit tests, I used Visual Studio Unit Testing Framework. To work through those exercises, you will need a minimum of the professional edition of Visual Studio to create and run the tests but the ultimate edition is recommended.

In addition to Visual Studio, you will need IIS for web-hosting your web API and Microsoft SQL Server 2012, either the Express edition or preferably the Developer edition, to be used as the persistence store. You will also need the browsers: mostly Internet Explorer 9.0 and Google Chrome in some specific cases. You’ll also need the HTTP debugging tool Fiddler (http://fiddler2.com/). For the exercises that require external .NET assemblies, you can use NuGet from Codeplex (http://nuget.codeplex.com/) to pull those packages into your project. For Chapter 12 on performance, in order to simulate some load, you will need Apache Bench (ab.exe), which is part of Apache HTTP Server.

Who This Book Is For

The book is for every .NET developer who wants to gain a solid and a practical hands-on understanding of the basics of the ASP.NET Web API framework. A good working knowledge of C# and the .NET framework 4.5, familiarity with Visual Studio 2012 are the only pre-requisites to benefit from this book, though a basic knowledge of the ASP.NET MVC framework and the HTTP protocol will be helpful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.206.225