Expert ASP.NET Web API 2 for MVC Developers

  • ฀Gain฀a฀solid฀architectural฀understanding฀of฀RESTful฀services฀
  • ฀Learn฀how฀to฀leverage฀the฀MVC฀pattern฀and฀components฀to฀build฀web฀services
  • ฀Generate฀and฀process฀JSON฀data฀from฀data฀models
  • ฀Learn฀what’s฀new฀in฀Web฀API฀2฀and฀how฀best฀to฀apply฀these฀new฀features฀
  • ฀Build฀secure฀and฀scalable฀web฀services฀that฀integrate฀with฀MVC฀applications
  • ฀Extend฀Web฀API฀2฀to฀customize฀it฀to฀your฀needs

  

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 Author .............................................................................................................

Part 1: Getting Ready ....................................................................................

   ■

Chapter 1: Getting Readys

   ■

Chapter 2: Your First Web API Application ........................................................................

   ■

Chapter 3: Essential Techniques ......................................................................................

   ■

Chapter 4: Understanding HTTP Web Services ................................................................

   ■

Chapter 5: SportsStore: Preparation ...............................................................................

   ■

Chapter 6: SportsStore: A RESTful Application

   ■

  

Chapter 7: SportsStore: Creating the Clients .................................................................

  

Chapter 8: SportsStore: Deployment .............................................................................

  Part 2: Results and Parameters ................................................................ ■

  

Chapter 9: The Anatomy of ASP.NET Web API ................................................................

  

Chapter 10: Creating and Configuring a Web API Application .......................................

  

Chapter 11: Action Method Results ...............................................................................

  

Chapter 12: Creating Media Type Formatters ................................................................

  

Chapter 13: Using the Built-in Media Formatters

  

Chapter 14: Understanding Parameter and Model Binding

  

Chapter 15: Binding Simple Data Types .........................................................................

  

Chapter 16: Binding Complex Data Types Part I ............................................................

  ■

  

Chapter 17: Binding Complex Data Types Part II ...........................................................

  

Chapter 18: Model Validation ........................................................................................

  Part 3: Dispatching Requests ................................................................... ■

  

Chapter 19: Dispatching Requests ................................................................................

  

Chapter 20: URL Routing: Part I .....................................................................................

  

Chapter 21: URL Routing: Part II ....................................................................................

  

Chapter 22: Controllers and Actions

  

Chapter 23: Filters Part I ...............................................................................................

  

Chapter 24: Filters Part II ..............................................................................................

  

Chapter 25: Error Handling ............................................................................................

  

Chapter 26: Using OWIN .................................................................................................

  PART I Getting Ready

CHAPTER 1

Getting Readys

  

Web API 2 is the latest evolution of Microsoft’s web services toolkit, which allows you to create RESTful applications

built on the ASP.NET platform. It provides a standards-based approach and a high-productivity development model

that makes it easy to deliver services to a wide range of clients, including mobile devices.

  

In this book, I take you right from creating your first Web API web services to the most advanced techniques

and features. No prior knowledge of HTTP web services or Web API is required. I start with the basics and explain everything you need to know. In short, this book will give you expert insight and understanding of how to create, customize, and deploy complex, flexible, and robust HTTP web services.

  

Web services don’t exist in isolation, so I also show you how to write browser-based single-page applications to

consume them. I demonstrate how these clients influence the way that Web API web services respond and how you

can adapt your web service to different client types.

  What Do You Need to Know?

You should be familiar with using the ASP.NET MVC framework to create web applications. This means you are able

to use Visual Studio to write C# classes and know how to use Razor and HTML to create views. The term Expert in the

title refers to the degree of depth that I cover in this book, and you don’t need any knowledge of Web API or HTTP web

services; however, if you don’t know how to use ASP.NET MVC, then you will struggle to follow many of the examples.

If you want to brush up on your knowledge of MVC, then read my Pro ASP.NET MVC 5 and Pro ASP.NET MVC Platform books, both published by Apress.

  What Does Expert Mean?

This book is for programmers who want to understand every aspect of web services development using ASP.NET Web

API. Or, put another way, you want to be an expert in Web API. I dig deeply into the details of how Web API works

behind the scenes in this book and give you a warts-and-all view of how Web API can be used to create sophisticated

and secure RESTful web services. You don’t have to know anything about Web API or HTTP web services before you

start. I build on your existing knowledge of the MVC framework to give you all the information you need.

  What Is the Structure of This Book? This book is split into three parts, each of which covers a set of related topics. Part 1: Getting Ready Part 1 of this book provides the information you need to get ready for the rest of the book. It includes this chapter and

a primer for the techniques you will need to follow the examples in this chapter. I also show you how to build your first

web service and single-page client and take you through the process of building a more realistic application, called SportsStore.

  Part 2: Results and Parameters Part 2 of this book focuses on the aspect of Web API that you will spend most of your time on during your first real projects: the data sent from clients and the responses that you produce in return. I explain how to create different

kinds of HTTP responses using Web API, how to master the data binding process that Web API uses to process request

data, and how to ensure that the data you receive from clients is valid.

  Part 3: Dispatching Requests Part 3 of this book explains how Web API dispatches HTTP requests from the moment they arrive from the client

until the response is generated. I describe all of the steps that a request goes through and show you how to configure

and customize just about every class and interface that Web API relies on to get fine-grain control over how your web services operate. I show you how Web API uses the URL routing system to support RESTful web services, how controllers and action methods are selected, and how to deal with errors and cross-cutting concerns. Many of these techniques are similar to the ones you know from MVC framework development, but Web API uses its own namespaces and classes and has a different approach than the one you are used to using.

  Are There Lots of Examples?

There are loads of examples. The best way to learn Web API is by example, and I have packed as many of them as I can

into this book. To maximize the number of examples in this book, I have adopted a simple convention to avoid listing

the contents of files over and over again. The first time I use a file in a chapter, I’ll list the complete contents, just as I

have in Listing 1-1.

  Listing 1-1. A Complete Example Document

  using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace SportsStore { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );

   config.Formatters.Remove(config.Formatters.XmlFormatter); } } }

  

This listing is taken from Chapter 6. Don’t worry about what it does; just be aware that the first time I use a file

in each chapter there will be complete listing, similar to Listing 1-1 shown here. For the second and subsequent examples, I show you just the elements that change, in a partial listing. You can spot a partial the listing because it starts and ends with ellipsis ( ...), as shown in Listing 1-2.

  Listing 1-2.

  A Partial Listing ...

  public Product GetProduct(int id) { Product result = Repository.Products.Where(p => p.Id == id).FirstOrDefault(); if (result == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); } else { return result; } } ...

  

This is a subsequent listing from Chapter 6. You can see that just the GetProduct method is shown and that I

have highlighted a number of statements. This is how I draw your attention to the part of the example that shows the

feature or technique I am describing. In a partial listing like this, only those parts shown have changed from the full

listing earlier in the chapter.

  

This convention lets me pack in more examples, but it does mean it can be hard to locate a specific technique.

To this end, all of the chapters in which I describe Web API features in Parts 2 and 3 begin with a summary table that

describes the techniques contained in the chapter and the listings that demonstrate how they are used.

  Where Can You Get the Example Code?

  You can download all of the examples for all of the chapters in this book fr . The download is available without charge and includes all of the supporting resources that are required to re-create the examples

without having to type them in. You don’t have to download the code, but it is the easiest way of experimenting with

the examples and cutting and pasting them into your own projects.

  

If you do want to re-create the examples from scratch, then you will find that every chapter contains detailed

listings of all the files I create and modify. I never refer you to an external file or hand-wave about leaving the rest of the example as an exercise; every detail you need to re-create every example is contained within this book.

How Do You Set Up a Development Environment?

  The most important software you need for this book is Visual Studio 2013, which contains everything you need to get started, including a built-in application server for running and debugging Web API applications, an administration-free edition of SQL Server for developing database-driven applications, and, of course, a code editor compiler and debugger. Getting Visual Studio There are several editions of Visual Studio, but I will be using the one that Microsoft makes available free of charge,

called Visual Studio Express 2013 for Web. Microsoft adds some nice features to the paid-for editions of Visual Studio,

but you will not need them for this book, and all of the figures that you see throughout this book have been taken using the Express edition, which you can download from

  There are several versions of Visual Studio 2013 Express, each of which is used for a different kind of development. Make sure you get the Web version, which supports ASP.NET applications.

  

Note All of the examples in this book will work with Visual Studio Express 2013 for Web, except those in Chapter 26

where I use Visual Studio Express 2013 for Windows Desktop, which allows me to create a console application.

  

I follow a specific approach to creating ASP.NET projects: I don’t use the predefined templates that Microsoft

provides, preferring to explicitly add all of the packages I require. This means more work is required to get set up, but

the benefit is that you end up with a much better understanding of how an application fits together. I provide a primer

in Chapter 2 that gives an example of what you can expect.

  ■ Tip Visual Studio includes NuGet for downloading and installing software packages. I use NuGet throughout this

book and always specify the version of each NuGet package so that you are sure to get the results that I demonstrate.

  

If you are in doubt, do which contains complete projects for

each chapter.

  Preparing Visual Studio Visual Studio Express contains all the features you need to create, test, and deploy Web API applications, but some

of those features are hidden away until you ask for them. To enable all of the features, select Expert Settings from the

Visual Studio Tools ➤ Settings menu.

  ■ Tip Microsoft has decided that the top-level menus in Visual Studio should be all in uppercase, which means that

the menu to which I just referred is really TOOLS. I think this is rather like shouting, and I will capitalize menu names like

Tools is here throughout this book.

Getting Google Chrome

  In this book, I use the Google Chrome browser. In part this is because it has some excellent F12 developer tools (so-called because they are accessed by pressing the F12 key) but also because using Chrome allows me to use Postman, an outstanding HTTP client that makes it easy to test web services by manually crafting HTTP requests.

  

You can download Chrome fr . Both are available without charge, but I encourage you to donate to the Postman developers if you find it useful.

  You will also need the Postman Interceptor extension, which increases the functionality and is available through

the Google Chrome Extension Store as a zero-cost installation. Click the Chrome settings button (the one with three

horizontal lines at the right side of the screen) and select Tools ➤ Extensions. Search for Postman Interceptor and follow the installation instructions.

  Selecting Chrome for Debugging

You can select Chrome as the browser that Visual Studio will start when you debug a project by selecting it from the

drop-down list of browsers, as shown in Figure

  Figure 1-1. Selecting Google Chrome in Visual Studio

Summary

  

In this chapter, I outlined the content and structure of this book and outlined the software that is required for Web API

web development. As I said earlier, the best way to learn Web API is by example, and in Chapter 2 I jump right in and

show you how to create your first web service and client application.

CHAPTER 2

Your First Web API Application

  

The best way to get a feel for a new technology is by applying it, so in this chapter I jump right in and demonstrate one

of the most common uses for Web API: adding an HTTP web service to an existing MVC framework application.

  

This is nowhere near as awkward as it might sound, not least because the MVC framework and Web API share a

common heritage and can use the same data models. In fact, you may be surprised at how little time I spend in this chapter creating the web service compared with building the example MVC framework application and writing the JavaScript code that consumes the web service in the browser.

  You don’t need to retrofit an HTTP web service to an existing application, of course, and in Chapters 5–8 I build a

more complex example that begins with Web API and puts the HTTP web service right at the heart of the development

process.

  

Note I start slowly in this chapter and spell out every detail. I’ll pick up the pace—and the depth of detail—in later

■ chapters, but I want to make clear the process by which I create projects and emphasize the relationship between the components in the application.

  Preparing the Example Project Visual Studio includes templates for different kinds of projects. The basic starting point is the Empty project, which

can be set up to include just the files and references required for an MVC or Web API application. Other options add

models, views, and controllers to help kick-start a project by providing commonly used features.

  

I prefer to work with the Empty template and just have Visual Studio add the minimum initial content—and I

recommend you do the same. This approach gives you greater insight into how an application is put together and where you need to start looking when something goes wrong. Throughout this book, I’ll be creating projects in the way that I describe here, so I’ll walk through the process step-by-step in this chapter so you know what to expect.

  

Note The example projects that I created in this chapter and in Chapters 5–8 are derived from the ones I used in Pro ASP.NET MVC 5. You don’t need to have any of my other books to understand the examples, but if you already have

a copy, then you may find it interesting to compare the different approaches required for creating a pure MVC framework application and one that integrates Web API. Creating the Visual Studio Project To get started, I created a new Visual Studio project. Select New Project from the File menu to open the New Project dialog window. Navigate through the Templates section to select the Visual C# ➤ Web ➤ ASP.NET Web Application template and set the name of the project to PartyInvites, as shown in Figur .

  Figure 2-1. Creating the new project Click the OK button to move to the New ASP.NET Project dialog window. Ensure that the Empty option is selected

and check the MVC and Web API options, as shown in Figurlick the OK button, and Visual Studio will create a

new project called PartyInvites.

  Figure 2-2.

   Selecting the ASP.NET project type

Adding and Updating NuGet Packages

  

One of the most useful enhancements to Visual Studio in recent years has been the addition of NuGet, which makes it

easy to download, install, and update software packages in a project.

  

I am going to be working with specific versions of NuGet packages in this book to make sure you are able to

re-create the examples and get the same results. The days where Microsoft made enormous releases of the entire .NET stack every 18 months have passed, and each piece of technology receives more frequent small updates. This

means the versions of the MVC and Web API that are added to projects by Visual Studio may not be the latest versions

available.

  

Select Package Manager Console from the Visual Studio Tools ➤ NuGet Package Manager menu and enter the

following commands to update the MVC and Web API packages, as well as the package that is used to process JSON

data (I describe JSON in more detail in Chapter 3):

  Update-Package microsoft.aspnet.mvc -version 5.1.1 Update-Package microsoft.aspnet.webapi -version 5.1.1 Update-Package Newtonsoft.json -version 6.0.1 There are two other packages that I rely on for the example application in this chapter and those in later chapters.

  

The first is Bootstrap, which is a CSS package that makes it easy to style the HTML generated by MVC views. I have no

visual design skills at all—to the extent that I was excused from art lessons at school and allowed to do extra math— but even I can hack together something that looks appealing with Bootstrap. I prefer to work with a real designer on complex projects, but for simple applications, Bootstrap works just fine.

  ■ Tip I don’t describe Bootstrap in this book, but you can get details of the CSS classes I apply at

  The second package I use is jQuery, which provides an abstraction layer that simplifies working with the HTML Document Object Model API and makes Ajax requests simpler and more elegant. jQuery is the de facto JavaScript

library for developing the client-side part of web applications and—just like Bootstrap—has recently been adopted by

Microsoft in the Visual Studio project templates. I provide a primer for using jQuery to make Ajax requests in Chapter 3.

  The final package I use is Knockout, which makes it easy to build an HTML client that responds dynamically to the

data returned by a web service or by interactions with the user. I give a brief introduction to using Knockout in Chapter 3.

To add Bootstrap, jQuery, and Knockout to the project, enter the following commands into the Package Manager Console:

  Install-Package jquery -version 2.1.0 Install-Package bootstrap -version 3.1.1 Install-Package knockoutjs –version 3.1.0

Setting the Port and Start URL

  The final preparations I need to make specify the TCP port that will be used to receive requests and the initial URL that will be passed to the browser when the project is started. Select Party Invites Properties from the Visual Studio Project menu and click Web to open the settings for ASP.NET projects.

  

Enable the Specific Page option and enter Home/Index in the field. On the same page, change the value in the

Project Url field to http://localhost:37993/ and click the Create Virtual Directory button. The first change prevents Visual Studio from trying to work out what URL should be shown when the application

starts based on the file you edited most recently, and the second change means that requests will be received on TCP

port 37993.

  Creating the MVC Application In this section, I create a simple MVC framework application that gathers responses from invitees to a party. This is

a variation on the project with which I start the Pro ASP.NET MVC 5 book, and I chose it to emphasize the ease with

which Web API can be applied to MVC framework applications. I spend much of the rest of the book explaining the

differences, so it is good to start with something that focuses on just how much you already know how to do.

  Creating the Model Now that I have created the project, I can add the model. The structure of a Web API application shares a lot with the MVC framework, which is one of the reasons that both technologies can coexist so well. I created a file called

  GuestResponse.cs in the Models folder and used it to define the class shown in Listing 2-1.

  Listing 2-1.

  The Contents of the GuestResponse.cs File

  using System.ComponentModel.DataAnnotations; namespace PartyInvites.Models { public class GuestResponse { [Required] public string Name { get; set; } [Required] public string Email { get; set; } [Required] public bool? WillAttend { get; set; } } }

  To create a simple model repository, I created a class file called Repository.cs in the Models folder and used it to define the class shown in Listing 2-2.

  Listing 2-2. The Contents of the Repository.cs File

  using System.Collections.Generic; namespace PartyInvites.Models { public class Repository { private static Dictionary<string, GuestResponse> responses; static Repository() { responses = new Dictionary<string, GuestResponse>(); responses.Add("Bob", new GuestResponse {Name = "Bob", Email="bob@example.com", WillAttend=true}); responses.Add("Alice", new GuestResponse { Name = "Alice", Email = "alice@example.com", WillAttend = true }); responses.Add("Paul", new GuestResponse { Name = "Paul", Email = "paul@example.com", WillAttend = true }); } public static void Add(GuestResponse newResponse) { string key = newResponse.Name.ToLowerInvariant(); if (responses.ContainsKey(key)) { responses[key] = newResponse; } else { responses.Add(key, newResponse); } } public static IEnumerable<GuestResponse> Responses { get { return responses.Values; } } } }

  The repository for this application is simple and stores its data objects as a collection in memory that is exposed

through static properties. This means the model state will be lost when the application is restarted, but it does allow

me to keep the example simple. (I show a more persistent model in Chapter 5 when I create a larger and more realistic

MVC/Web API application that stores its model in a database.) In the static constructor, I add some default data so that the model is populated with responses.

  Creating the MVC Controller My next step is to create an MVC controller that will generate content and receive form data from my application clients. Web API also has controllers—as you will see in the “Creating the Web Service” section—and I will be clear about which kind of controller I am using throughout this book. I created an MVC controller by right-clicking the Controllers folder and selecting Add ➤ Controller from the pop-up menu. Figurws the options that Visual Studio presents for creating controllers for both MVC and Web API.

  Figure 2-3. Selecting a controller type

Visual Studio is able to generate a templated set of action methods for controllers, but I will be using empty

controllers for both MVC and Web API throughout this book. Just as with the project template, I prefer to define just

the code I need for my applications, and I follow the same approach for the examples in this book so that you know where every action methods comes from and why I have added it.

  I selected the MVC 5 Controller – Empty option from the list, clicked the Add button, and set the name to HomeController, as shown in Figure .

  Figure 2-4. Creating an MVC controller

Clicking the Add button creates the Controllers/HomeController.cs file, which I used to define the controller

shown in Listing 2-3.

  Listing 2-3. The Contents of the HomeController.cs File

  using System.Web.Mvc; using PartyInvites.Models; using System.Linq; namespace PartyInvites.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Rsvp() { return View(); } [HttpPost] public ActionResult Rsvp(GuestResponse response) { if (ModelState.IsValid) { Repository.Add(response); return View("Thanks", response); } else { return View(); } } [ChildActionOnly] public ActionResult Attendees() { return View(Repository.Responses.Where(x => x.WillAttend == true)); } } }

  Index action simply renders a view that welcomes the user to

  The controller defines four action methods. The

  Rsvp methods allow the user to populate the fields of a GuestResponse model object through

  the application. The model binding and validate using the model state feature. When the user submits a complete set of values for the

  GuestResponse object (enforced by the use of the Required attribute in Listing 2-1), I update the repository and

  

render a view called Thanks. The final action method can be called only as a child action, and it returns the collection

of GuestResponse objects that represent users who have indicated they will attend.

  This is a pretty basic controller, but it captures the core characteristics of most MVC framework applications, albeit on a simplified basis. Operations are performed on the repository, form data values are bound to object properties using model binding, and action methods are set up to be invoked based on the HTTP verb used in the request.

  Creating the Views

I need to create a layout and four views for my example application. I created the Views/Shared folder, and Listing 2-4

shows the _Layout.cshtml file I added to it, which contains references for the Bootstrap, jQuery, and Knockout files.

  Listing 2-4.

  The Contents of the _Layout.cshtml File

  <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <script src="~/Scripts/jquery-2.1.0.min.js"></script> <script src="~/Scripts/knockout-3.1.0.js"></script> <link href="~/Content/bootstrap.css" rel="stylesheet" /> <link href="~/Content/bootstrap-theme.css" rel="stylesheet" /> <title>@ViewBag.Title</title> <style> body { padding-top: 10px; } </style> </head> <body class="container"> @RenderBody() </body> </html>

  

Listing 2-5 shows the Index.cshtml file that I created by right-clicking the Index action method in the Home

controller and selecting Add View from the pop-up menu. I set View Name to Index, ensured that the Use a Layout Page option is checked, and clicked the Add button to create the view file. (Visual Studio also creates the

  Views/_ViewStart.cshtml file, which ensures that the _Layout.cshtml file I created in Listing 2-4 is applied.)

  Listing 2-5. The Contents of the Index.cshtml File

  @{ ViewBag.Title = "Party!";} <div class="text-center"> <h2>We're going to have an exciting party!</h2> <h3>And you are invited.</h3> @Html.ActionLink("RSVP Now", "Rsvp", null, new { @class="btn btn-success"}) </div>

  

This view doesn’t contain any model data, but it does use the routing system to generate a link element that

targets the Rsvp action method on the same controller. Listing 2-6 shows the view that the Rsvp action renders, which

is the Rsvp.cshtml file I added to the /Views/Home folder.

  Listing 2-6.

  The Contents of the Rsvp.cshtml File

  @model PartyInvites.Models.GuestResponse @{ ViewBag.Title = "Rsvp"; } <div class="panel panel-success"> <div class="panel-heading"><h4>RSVP</h4></div> <div class="panel-body"> @using (Html.BeginForm()) { <div class="form-group"> <label>Your name:</label> @Html.TextBoxFor(x => x.Name, new { @class = "form-control" }) </div> <div class="form-group"> <label>Your email:</label> @Html.TextBoxFor(x => x.Email, new { @class = "form-control" }) </div> <div class="form-group"> <label>Will you attend?</label> @Html.DropDownListFor(x => x.WillAttend, new[] { new SelectListItem() {Text = "Yes, I'll be there", Value = bool.TrueString}, new SelectListItem() {Text = "No, I can't come", Value = bool.FalseString} }, "Choose an option", new { @class = "form-control" }) </div> <div class="text-center"> <input class="btn btn-success" type="submit" value="Submit RSVP" /> </div> } </div> </div>

This view contains a standard HTML form that collects values from the user via input and select elements.

  When the user submits the form with valid data, the Thanks.cshtml view in the Views/Home folder is rendered. You can see the contents of the Thanks.cshtml file in Listing 2-7.

  Listing 2-7. The Contents of the Thanks.cshtml File

  @model PartyInvites.Models.GuestResponse @{ ViewBag.Title = "Thanks";} <h1>Thank you, @Model.Name!</h1> <div class="lead"> @if (Model.WillAttend == true) { @:It's great that you're coming. The drinks are already in the fridge! @Html.Action("Attendees", "Home") } else { @:Sorry to hear that you can't make it, but thanks for letting us know.

   } </div>

  If the user has indicated that they will attend the party, then I use the Html.Action helper to invoke the

  Attendees child action method, which renders the /Views/Home/Attendees.cshtml view file, whose contents are shown in Listing 2-8.

  Listing 2-8.

  The Contents of the Attendees.cshtml File

  @model IEnumerable<PartyInvites.Models.GuestResponse> @if (Model.Count() == 1) { <p>You are the first to accept! Hurrah!</p> } else { <p>Here is the list of cool people coming: @string.Join(", ", Model.Select(x => x.Name))</p> }

  Using the MVC Application

To test the basic functionality, start the application and navigate to the /Home/Index URL. Click the RSVP Now button,

fill out the form, and click Submit RSVP. Figurws the different views rendered by the application.

  Figure 2-5.

   Testing the example application

  

Tip If you get an error telling you that the Attendees action is accessible only as a child request, it is because Visual

Studio has tried to be helpful and has told the browser to navigate to the /Home/Attendees URL because that is the last

view you were editing. Navigate to /Home/Index , and everything will be fine.

  Google Chrome, like all modern browsers, contains some useful developer tools, known as the F12 tools because

they are opened by pressing F12 on the keyboard. Before adding Web API to the application, I am going to use the F12

tools to measure the number of requests and the total amount of data sent from the server.

  

Getting an honest assessment of the requests required to go through the RSVP process entails some specific

steps, switching between the browser window that displays the applications and the F12 tools. Here is the sequence:

  1. Open the F12 tools, click the Network tab and check the Preserve Log option so that the list of network requests isn’t cleared for each new request.

  2. Ensure that the first icon in the toolbar, which is a circle, is red, indicating that Chrome will record the network requests it makes. If the circle isn’t red, then click it so that it is.

  3. Ensure that the browser window is showing the /Home/Index URL.

  4. Click the Clear button on the F12 toolbar (it is next to the red circle button).

  5. Right-click the Reload icon in the browser window and select Empty Cache and Hard Reload from the pop-up menu, as shown in Figur

  Figure 2-6.

   Clearing the cache and reloading the page 6.

  Click the RSVP Now button in the browser window, complete the form, and click the Submit RSVP button to send the form data to the server.

  Tip ■ The menu shown in F is available only when the F12 tools window is open.

  

The F12 Network tab will detail requests that the browser makes as you work through the example application.

Not all of these are for action methods—I added link and script elements to the _Layout.cshtml file, which is used as the layout for all the views and so the Bootstrap and JavaScript files have to be loaded from the server. (This happens just for the initial request so that the files are in the browser cache. You can see which requests are cached

by the browser by looking at the Size column.) At the bottom of the F12 window, Chrome displays a summary of the

requests it has made, and I have put my results in Table . Don’t worry if you get different numbers; I just want to give an illustrative reference.

  Table 2-1.

   The Request Summary from Google Chrome

  Description Value Total number of requests 21, of which 13 were made to the server and 8 were satisfied using the browser cache Total amount of data 247KB Creating the Web Service

Now that I have a basic MVC framework application in place, I can add some Web API functionality to create a web

service that exposes my RSVP model to HTTP clients. In the sections that follow, you will see just how easy it is to use

MVC and Web API side-by-side.

  

Tip Adding an HTTP web service to an existing MVC framework isn’t the only way to use Web API, but it is the one

I have started with in this book because it is such a common task. It also lets me demonstrate how much commonality

there is between MVC and Web API and how that commonality can be leveraged for quick results. In Chapter 6, I show

you a more considered approach to using Web API when I start by designing the web service first.

Creating the Web API Controller

  

Just like MVC, Web API uses controllers that define action methods that handle HTTP requests. I created a Web API

controller by right-clicking the Controllers folder, selecting Add ➤ Controller from the pop-up menu, and selecting

Web API 2 Controller – Empty from the list of controller types, as shown in Figur

  Figure 2-7. Adding a Web API controller Just as with MVC controllers, Visual Studio can create controllers with templated content. I’ll be using the empty controller for Web API throughout this book so that I can explain the purpose of all the code statements I use. Click

the Add button once you have selected the type, set the name of the new controller to RsvpController, and click the

Add button to create the Controllers/RsvpController.cs file. Listing 2-9 shows the action methods that I added to

the RsvpController class to create a simple web service.

  Listing 2-9. The Contents of the RsvpController.cs File

  using System.Collections.Generic; using System.Linq; using System.Web.Http; using PartyInvites.Models; namespace PartyInvites.Controllers { public class RsvpController : ApiController { public IEnumerable<GuestResponse> GetAttendees() { return Repository.Responses.Where(x => x.WillAttend == true); }

   public void PostResponse(GuestResponse response) { if (ModelState.IsValid) { Repository.Add(response); } } } }

  

The first thing to notice about my controller is that the base class is ApiController, which is defined in the

  System.Web.Http namespace. This is a different base class and namespace than an MVC controller uses because Web

  

API doesn’t use the standard System.Web and System.Web.Mvc namespaces. Instead, Web API uses separate classes,

even for functionality that is shared with MVC, such as filter attributes. Hover the mouse over the HttpGet or HttpPost

attributes in the code editor, and the pop-up box will tell you that these are classes defined in the System.Web.Http namespace, not the System.Web.Mvc namespace that defines the attribute I applied to the Home MVC controller.

  ■ Tip The fact that MVC and Web API have distinct versions of classes with the same names that perform the same function is confusing and is the most common cause of errors for developers new to Web API. Be careful that you don’t add the System.Web.Mvc namespace to Web API controllers.

  Next, notice that the result from the GetAttendees action method is an enumeration of my GuestResponse model

class. Web services deliver data to their clients and don’t use views to generate HTML content, so there is no need for