Expert ASP NET web API 2 for MVC developers

665 1.6K 0
Expert ASP NET web API 2 for MVC developers

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info 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 www.it-ebooks.info Contents at a Glance About the Author������������������������������������������������������������������������������������������������������������� xxiii About the Technical Reviewer������������������������������������������������������������������������������������������ xxv ■■Part 1: Getting Ready������������������������������������������������������������������������������������ ■■Chapter 1: Getting Readys�������������������������������������������������������������������������������������������������3 ■■Chapter 2: Your First Web API Application������������������������������������������������������������������������9 ■■Chapter 3: Essential Techniques��������������������������������������������������������������������������������������35 ■■Chapter 4: Understanding HTTP Web Services����������������������������������������������������������������57 ■■Chapter 5: SportsStore: Preparation�������������������������������������������������������������������������������69 ■■Chapter 6: SportsStore: A RESTful Application����������������������������������������������������������������99 ■■Chapter 7: SportsStore: Creating the Clients�����������������������������������������������������������������131 ■■Chapter 8: SportsStore: Deployment�����������������������������������������������������������������������������169 ■■Part 2: Results and Parameters���������������������������������������������������������������� 179 ■■Chapter 9: The Anatomy of ASP.NET Web API����������������������������������������������������������������181 ■■Chapter 10: Creating and Configuring a Web API Application���������������������������������������191 ■■Chapter 11: Action Method Results�������������������������������������������������������������������������������215 ■■Chapter 12: Creating Media Type Formatters����������������������������������������������������������������243 ■■Chapter 13: Using the Built-in Media Formatters����������������������������������������������������������267 ■■Chapter 14: Understanding Parameter and Model Binding�������������������������������������������297 ■■Chapter 15: Binding Simple Data Types������������������������������������������������������������������������325 ■■Chapter 16: Binding Complex Data Types Part I������������������������������������������������������������351 v www.it-ebooks.info ■ Contents at a Glance ■■Chapter 17: Binding Complex Data Types Part II�����������������������������������������������������������389 ■■Chapter 18: Model Validation����������������������������������������������������������������������������������������427 ■■Part 3: Dispatching Requests������������������������������������������������������������������� 449 ■■Chapter 19: Dispatching Requests��������������������������������������������������������������������������������451 ■■Chapter 20: URL Routing: Part I�������������������������������������������������������������������������������������483 ■■Chapter 21: URL Routing: Part II������������������������������������������������������������������������������������511 ■■Chapter 22: Controllers and Actions������������������������������������������������������������������������������535 ■■Chapter 23: Filters Part I�����������������������������������������������������������������������������������������������567 ■■Chapter 24: Filters Part II����������������������������������������������������������������������������������������������599 ■■Chapter 25: Error Handling��������������������������������������������������������������������������������������������623 ■■Chapter 26: Using OWIN�������������������������������������������������������������������������������������������������645 Index���������������������������������������������������������������������������������������������������������������������������������651 vi www.it-ebooks.info Part I Getting Ready www.it-ebooks.info Chapter Getting Readys Web API 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 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 www.it-ebooks.info Chapter ■ Getting Readys Part 1: Getting Ready Part 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 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 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 } );   www.it-ebooks.info Chapter ■ Getting Readys config.Formatters.Remove(config.Formatters.XmlFormatter); } } }   This listing is taken from Chapter 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 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 and 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 from www.apress.com 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 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 www.it-ebooks.info Chapter ■ Getting Readys 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 www.visualstudio.com 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 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, download the source code for this book from www.apress.com, 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 from https://www.google.com/chrome/browser and, once it is installed, get the Postman client from www.getpostman.com Both are available without charge, but I encourage you to donate to the Postman developers if you find it useful www.it-ebooks.info Chapter ■ Getting Readys 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 1-1 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 I jump right in and show you how to create your first web service and client application www.it-ebooks.info ■ Contents Using Knockout���������������������������������������������������������������������������������������������������������������������������54 Applying the Bindings������������������������������������������������������������������������������������������������������������������������������������������ 54 Summary�������������������������������������������������������������������������������������������������������������������������������������56 ■■Chapter 4: Understanding HTTP Web Services����������������������������������������������������������������57 Understanding ASP.NET Web API�������������������������������������������������������������������������������������������������57 Understanding Single-Page Applications������������������������������������������������������������������������������������������������������������ 58 Understanding Native Applications���������������������������������������������������������������������������������������������������������������������� 59 Understanding Shared-Model Applications��������������������������������������������������������������������������������������������������������� 59 Understanding Service Applications�������������������������������������������������������������������������������������������������������������������� 60 Understanding Simple Web Services������������������������������������������������������������������������������������������61 Understanding RESTful Web Services�����������������������������������������������������������������������������������������62 Embracing HTTP�������������������������������������������������������������������������������������������������������������������������������������������������� 63 Adding Data Discovery���������������������������������������������������������������������������������������������������������������������������������������� 65 Summary�������������������������������������������������������������������������������������������������������������������������������������67 ■■Chapter 5: SportsStore: Preparation�������������������������������������������������������������������������������69 Preparing the Example Project����������������������������������������������������������������������������������������������������69 Adding and Updating NuGet Packages ��������������������������������������������������������������������������������������������������������������� 72 Creating a Prep Controller����������������������������������������������������������������������������������������������������������������������������������� 73 Creating a Razor Layout�������������������������������������������������������������������������������������������������������������������������������������� 73 Creating the OWIN Startup Class������������������������������������������������������������������������������������������������������������������������� 74 Setting the TCP Port��������������������������������������������������������������������������������������������������������������������������������������������� 75 Creating the Product and Order Models��������������������������������������������������������������������������������������75 Defining the Model Classes��������������������������������������������������������������������������������������������������������������������������������� 75 Creating the Repository Classes�������������������������������������������������������������������������������������������������������������������������� 77 Testing the Repository����������������������������������������������������������������������������������������������������������������������������������������� 82 Checking the Database Schema�������������������������������������������������������������������������������������������������������������������������� 86 Configuring ASP.NET Identity ������������������������������������������������������������������������������������������������������87 Defining the User and Role Classes��������������������������������������������������������������������������������������������������������������������� 87 Creating the Database Context Classes��������������������������������������������������������������������������������������������������������������� 88 Creating the Manager Classes����������������������������������������������������������������������������������������������������������������������������� 90 ix www.it-ebooks.info ■ Contents Adding the Configuration Statements������������������������������������������������������������������������������������������������������������������ 92 Testing ASP.NET Identity ������������������������������������������������������������������������������������������������������������������������������������� 93 Removing the Application Cookie������������������������������������������������������������������������������������������������������������������������ 97 Summary�������������������������������������������������������������������������������������������������������������������������������������98 ■■Chapter 6: SportsStore: A RESTful Application����������������������������������������������������������������99 Creating a RESTful Web Service��������������������������������������������������������������������������������������������������99 Testing the Products Web Service��������������������������������������������������������������������������������������������������������������������� 101 Putting the Web Service in Context�������������������������������������������������������������������������������������������102 Working with Regular C# Objects ��������������������������������������������������������������������������������������������������������������������� 102 Using the RESTful Action Method Convention �������������������������������������������������������������������������������������������������� 103 Configuring Serialization�����������������������������������������������������������������������������������������������������������104 Adding Basic Data Validation�����������������������������������������������������������������������������������������������������106 Securing the Product Web Service��������������������������������������������������������������������������������������������109 Restricting Access to Action Method����������������������������������������������������������������������������������������������������������������� 110 Authenticating Requests ���������������������������������������������������������������������������������������������������������������������������������� 111 Adding Model Validation������������������������������������������������������������������������������������������������������������118 Applying Validation Attributes ��������������������������������������������������������������������������������������������������������������������������� 119 Validating the Model ����������������������������������������������������������������������������������������������������������������������������������������� 120 Adding Simple Dependency Injection����������������������������������������������������������������������������������������121 Recapping the Problem������������������������������������������������������������������������������������������������������������������������������������� 121 Creating the Dependency Resolver ������������������������������������������������������������������������������������������������������������������� 121 Using the Dependency Resolver in the Controller Class ����������������������������������������������������������������������������������� 123 Creating a Non-RESTful Web Service����������������������������������������������������������������������������������������124 Preparing the Routing Configuration ���������������������������������������������������������������������������������������������������������������� 124 Preparing the Model Objects����������������������������������������������������������������������������������������������������������������������������� 125 Preventing Formatting Loops���������������������������������������������������������������������������������������������������������������������������� 126 Defining the Web API Controller ������������������������������������������������������������������������������������������������������������������������ 127 Completing the Product Controller��������������������������������������������������������������������������������������������128 Summary�����������������������������������������������������������������������������������������������������������������������������������129 x www.it-ebooks.info ■ Contents ■■Chapter 7: SportsStore: Creating the Clients�����������������������������������������������������������������131 Preparing the Example Project��������������������������������������������������������������������������������������������������131 Setting Up JavaScript IntelliSense �������������������������������������������������������������������������������������������������������������������� 132 Updating the Layout������������������������������������������������������������������������������������������������������������������������������������������ 132 Implementing the Common Code����������������������������������������������������������������������������������������������133 Defining the Ajax Layer�������������������������������������������������������������������������������������������������������������������������������������� 133 Defining the Model�������������������������������������������������������������������������������������������������������������������������������������������� 135 Defining the Authentication Controller �������������������������������������������������������������������������������������������������������������� 136 Defining the Products Controller����������������������������������������������������������������������������������������������������������������������� 138 Defining the Orders Controller �������������������������������������������������������������������������������������������������������������������������� 142 Creating the Customer Client����������������������������������������������������������������������������������������������������145 Creating the Customer Model ��������������������������������������������������������������������������������������������������������������������������� 145 Creating the Customer Controller���������������������������������������������������������������������������������������������������������������������� 146 Creating the Views �������������������������������������������������������������������������������������������������������������������������������������������� 149 Creating the Administration Client��������������������������������������������������������������������������������������������159 Creating the Admin Model��������������������������������������������������������������������������������������������������������������������������������� 159 Creating the Admin Controller��������������������������������������������������������������������������������������������������������������������������� 159 Creating the Views��������������������������������������������������������������������������������������������������������������������������������������������� 160 Testing the Admin Client ����������������������������������������������������������������������������������������������������������������������������������� 165 Summary�����������������������������������������������������������������������������������������������������������������������������������167 ■■Chapter 8: SportsStore: Deployment�����������������������������������������������������������������������������169 Preparing the SportsStore Application��������������������������������������������������������������������������������������169 Preventing the Product Database from Resetting��������������������������������������������������������������������������������������������� 169 Adding Database Connection Strings���������������������������������������������������������������������������������������������������������������� 171 Preparing Azure�������������������������������������������������������������������������������������������������������������������������172 Creating the Databases������������������������������������������������������������������������������������������������������������������������������������� 172 Creating the Web Site���������������������������������������������������������������������������������������������������������������������������������������� 175 Downloading the Publish Profile������������������������������������������������������������������������������������������������������������������������ 175 xi www.it-ebooks.info ■ Contents Deploying the Application ���������������������������������������������������������������������������������������������������������176 Configuring the Databases�������������������������������������������������������������������������������������������������������������������������������� 177 Publishing the Application ��������������������������������������������������������������������������������������������������������177 Summary�����������������������������������������������������������������������������������������������������������������������������������178 ■■Part 2: Results and Parameters���������������������������������������������������������������� 179 ■■Chapter 9: The Anatomy of ASP.NET Web API����������������������������������������������������������������181 Understanding the Web API Namespaces and Types�����������������������������������������������������������������181 Understanding the Web API Context Objects�����������������������������������������������������������������������������183 Getting Information About the Request������������������������������������������������������������������������������������������������������������� 184 Getting Information About the Controller����������������������������������������������������������������������������������������������������������� 185 Getting Information About Everything Else�������������������������������������������������������������������������������������������������������� 186 Understanding the Web API Components����������������������������������������������������������������������������������186 Application Configuration���������������������������������������������������������������������������������������������������������������������������������� 187 Controllers, Actions, and Results����������������������������������������������������������������������������������������������������������������������� 187 Services������������������������������������������������������������������������������������������������������������������������������������������������������������� 187 Dispatchers and Handlers��������������������������������������������������������������������������������������������������������������������������������� 189 Summary�����������������������������������������������������������������������������������������������������������������������������������190 ■■Chapter 10: Creating and Configuring a Web API Application���������������������������������������191 Preparing the Example Project��������������������������������������������������������������������������������������������������191 Creating the Model and Repository������������������������������������������������������������������������������������������������������������������� 192 Creating an HTTP Web Service�������������������������������������������������������������������������������������������������������������������������� 193 Creating the Browser Client������������������������������������������������������������������������������������������������������������������������������� 194 Testing the Example Application������������������������������������������������������������������������������������������������������������������������ 197 Configuring a Web API Application��������������������������������������������������������������������������������������������199 Configuring Web API Through the ASP.NET Platform������������������������������������������������������������������������������������������ 199 Understanding the Configuration Object������������������������������������������������������������������������������������������������������������ 201 Configuring Web API Dependency Injection�������������������������������������������������������������������������������202 Preparing for Dependency Injection������������������������������������������������������������������������������������������������������������������ 203 Understanding the Web API Dependency Interfaces������������������������������������������������������������������������������������������ 204 Installing the Dependency Injection Container�������������������������������������������������������������������������������������������������� 206 xii www.it-ebooks.info ■ Contents Implementing the Dependency Interfaces��������������������������������������������������������������������������������������������������������� 206 Configuring Web API������������������������������������������������������������������������������������������������������������������������������������������ 209 Configuring Dependency Injection for Web API and MVC����������������������������������������������������������210 Declaring the Dependency��������������������������������������������������������������������������������������������������������������������������������� 210 Installing the Dependency Injection Packages�������������������������������������������������������������������������������������������������� 211 Adding MVC Support to the Resolver����������������������������������������������������������������������������������������������������������������� 211 Configuring the MVC Framework����������������������������������������������������������������������������������������������������������������������� 213 Summary�����������������������������������������������������������������������������������������������������������������������������������214 ■■Chapter 11: Action Method Results�������������������������������������������������������������������������������215 Preparing the Example Project��������������������������������������������������������������������������������������������������215 Understanding Action Method Results �������������������������������������������������������������������������������������217 Returning No Result �����������������������������������������������������������������������������������������������������������������218 Consuming a No Result Action Method������������������������������������������������������������������������������������������������������������� 219 Returning an Action Result �������������������������������������������������������������������������������������������������������222 Understanding the IHttpActionResult Interface������������������������������������������������������������������������������������������������� 223 Using the ApiController Action Result Methods������������������������������������������������������������������������������������������������� 224 Returning Other Status Codes��������������������������������������������������������������������������������������������������������������������������� 226 Creating a Custom Action Result����������������������������������������������������������������������������������������������������������������������� 228 Returning Model Data���������������������������������������������������������������������������������������������������������������230 Understanding the Default Behavior ����������������������������������������������������������������������������������������������������������������� 230 Understanding the Content Negotiation Process����������������������������������������������������������������������������������������������� 231 Implementing a Custom Content Negotiator ���������������������������������������������������������������������������������������������������� 232 Bypassing Content Negotiation������������������������������������������������������������������������������������������������������������������������� 238 Returning Negotiable Action Results ����������������������������������������������������������������������������������������239 Creating Negotiable Action Results������������������������������������������������������������������������������������������������������������������� 239 Summary�����������������������������������������������������������������������������������������������������������������������������������241 ■■Chapter 12: Creating Media Type Formatters����������������������������������������������������������������243 Preparing the Example Project��������������������������������������������������������������������������������������������������244 Creating a Media Type Formatter����������������������������������������������������������������������������������������������245 Implementing a Basic Media Type Formatter���������������������������������������������������������������������������������������������������� 246 xiii www.it-ebooks.info ■ Contents Refining the Custom Formatter�������������������������������������������������������������������������������������������������252 Supporting Content Encodings�������������������������������������������������������������������������������������������������������������������������� 252 Setting the HTTP Response Headers����������������������������������������������������������������������������������������������������������������� 255 Participating in the Negotiation Process�����������������������������������������������������������������������������������257 Creating a Media Type Mapping������������������������������������������������������������������������������������������������������������������������ 258 Using the Mapping Extension Methods������������������������������������������������������������������������������������������������������������� 261 Creating Per-Request Media Type Formatters���������������������������������������������������������������������������263 Creating the Formatter Instance������������������������������������������������������������������������������������������������������������������������ 264 Testing the Per-Request Formatter ������������������������������������������������������������������������������������������������������������������� 265 Summary�����������������������������������������������������������������������������������������������������������������������������������266 ■■Chapter 13: Using the Built-in Media Formatters����������������������������������������������������������267 Preparing the Example Project��������������������������������������������������������������������������������������������������268 Working with the Built-in Media Type Formatters���������������������������������������������������������������������269 Listing the Built-in Media Type Formatters�������������������������������������������������������������������������������������������������������� 269 Dealing with Type Matching During Negotiation������������������������������������������������������������������������������������������������ 272 Working with the JSON Media Type Formatter �������������������������������������������������������������������������281 Configuring the JSON Media Type Formatter���������������������������������������������������������������������������������������������������� 282 Configuring Json.Net����������������������������������������������������������������������������������������������������������������������������������������� 284 Using the XML Media Type Formatter���������������������������������������������������������������������������������������293 Configuring the XML Media Type Formatter ����������������������������������������������������������������������������������������������������� 293 Getting the Xml Media Type Formatter Working ����������������������������������������������������������������������������������������������� 294 Summary�����������������������������������������������������������������������������������������������������������������������������������296 ■■Chapter 14: Understanding Parameter and Model Binding�������������������������������������������297 Preparing the Example Project��������������������������������������������������������������������������������������������������298 Creating the Controller ������������������������������������������������������������������������������������������������������������������������������������� 298 Creating the Client �������������������������������������������������������������������������������������������������������������������������������������������� 298 Adding a New Route ����������������������������������������������������������������������������������������������������������������������������������������� 300 Testing the Example Application ����������������������������������������������������������������������������������������������������������������������� 301 xiv www.it-ebooks.info ■ Contents Understanding the Default Binding Behavior ���������������������������������������������������������������������������302 Understanding Parameter Binding ������������������������������������������������������������������������������������������������������������������� 303 Understanding Model Binding��������������������������������������������������������������������������������������������������������������������������� 307 Performing Binding Customizations �����������������������������������������������������������������������������������������312 Binding Complex Types from the Request URL�������������������������������������������������������������������������������������������������� 312 Binding Simple Types from the Request Body��������������������������������������������������������������������������������������������������� 314 Defining a Binding Rule������������������������������������������������������������������������������������������������������������������������������������� 316 Manually Obtaining Request Values������������������������������������������������������������������������������������������318 Handling POST Requests ���������������������������������������������������������������������������������������������������������������������������������� 322 Summary�����������������������������������������������������������������������������������������������������������������������������������324 ■■Chapter 15: Binding Simple Data Types������������������������������������������������������������������������325 Preparing the Example Project��������������������������������������������������������������������������������������������������325 Preparing the Common Code����������������������������������������������������������������������������������������������������328 Working with Value Providers and Value Provider Factories�����������������������������������������������������329 Understanding Value Providers and Value Provider Factories��������������������������������������������������������������������������� 330 Creating a Custom Value Provider and Factory ������������������������������������������������������������������������������������������������ 332 Applying a Custom Value Provider and Factory ������������������������������������������������������������������������334 Understanding How Web API Looks for Values ������������������������������������������������������������������������������������������������� 334 Applying a Value Provider Factory with an Attribute ���������������������������������������������������������������������������������������� 335 Extending the Default Behavior������������������������������������������������������������������������������������������������������������������������� 340 Creating a Parameter Binding Rule ������������������������������������������������������������������������������������������������������������������ 344 Summary�����������������������������������������������������������������������������������������������������������������������������������350 ■■Chapter 16: Binding Complex Data Types Part I������������������������������������������������������������351 Preparing the Example Project��������������������������������������������������������������������������������������������������351 Using the Built-in Model Binders�����������������������������������������������������������������������������������������������354 Binding Objects������������������������������������������������������������������������������������������������������������������������������������������������� 355 Broadening the Source of Binding Values �������������������������������������������������������������������������������������������������������� 359 Binding Collections and Arrays�������������������������������������������������������������������������������������������������������������������������� 362 Binding Key-Value Pairs������������������������������������������������������������������������������������������������������������������������������������ 366 xv www.it-ebooks.info ■ Contents Working with Custom Model Binders����������������������������������������������������������������������������������������368 Preparing the Application���������������������������������������������������������������������������������������������������������������������������������� 368 Understanding Model Binders �������������������������������������������������������������������������������������������������������������������������� 370 Creating a Custom Model Binder����������������������������������������������������������������������������������������������������������������������� 372 Applying a Custom Model Binder���������������������������������������������������������������������������������������������������������������������� 376 Using Type Converters���������������������������������������������������������������������������������������������������������������382 Understanding Type Converters ������������������������������������������������������������������������������������������������������������������������ 382 Creating a Type Converter��������������������������������������������������������������������������������������������������������������������������������� 383 Applying a Type Converter��������������������������������������������������������������������������������������������������������������������������������� 384 Summary�����������������������������������������������������������������������������������������������������������������������������������387 ■■Chapter 17: Binding Complex Data Types Part II�����������������������������������������������������������389 Preparing the Example Project��������������������������������������������������������������������������������������������������390 Testing the Application�������������������������������������������������������������������������������������������������������������������������������������� 392 Creating a Custom Media Type Formatter���������������������������������������������������������������������������������393 Preparing the Client������������������������������������������������������������������������������������������������������������������������������������������� 394 Creating the Media Type Formatter������������������������������������������������������������������������������������������������������������������� 395 Registering and Testing the Media Type Formatter������������������������������������������������������������������������������������������� 400 Using the Built-in Media Type Formatters���������������������������������������������������������������������������������401 Handling URL-Encoded Data������������������������������������������������������������������������������������������������������������������������������ 402 Handling JSON Requests����������������������������������������������������������������������������������������������������������������������������������� 411 Handling XML Requests ������������������������������������������������������������������������������������������������������������������������������������ 414 Customizing the Model Binding Process�����������������������������������������������������������������������������������420 Changing the Behavior of the Default Action Value Binder�������������������������������������������������������������������������������� 421 Creating a Custom Action Value Binder������������������������������������������������������������������������������������������������������������� 424 Summary�����������������������������������������������������������������������������������������������������������������������������������425 ■■Chapter 18: Model Validation����������������������������������������������������������������������������������������427 Preparing the Example Project��������������������������������������������������������������������������������������������������427 Testing the Changes������������������������������������������������������������������������������������������������������������������������������������������ 430 Understanding Common Data Problems�����������������������������������������������������������������������������������431 Understanding Under-Posting���������������������������������������������������������������������������������������������������������������������������� 431 xvi www.it-ebooks.info ■ Contents Understanding Over-Posting������������������������������������������������������������������������������������������������������������������������������ 433 Understanding Bad Data������������������������������������������������������������������������������������������������������������������������������������ 434 Using Web API Model Validation������������������������������������������������������������������������������������������������436 Understanding Model State������������������������������������������������������������������������������������������������������������������������������� 436 Testing the Model State������������������������������������������������������������������������������������������������������������������������������������� 438 Removing the Debug Output Code��������������������������������������������������������������������������������������������������������������������� 439 Using the Binding Control Attributes�����������������������������������������������������������������������������������������439 Performing Validation with Validation Attributes�����������������������������������������������������������������������441 Using the Built-in Validation Attributes�������������������������������������������������������������������������������������������������������������� 441 Creating a Self-validating Model Class�������������������������������������������������������������������������������������443 Performing Validation in a Media Type Formatter���������������������������������������������������������������������444 Creating a Validating Media Type Formatter������������������������������������������������������������������������������������������������������ 445 Registering and Using the Custom Media Type Formatter�������������������������������������������������������������������������������� 447 Summary�����������������������������������������������������������������������������������������������������������������������������������448 ■■Part 3: Dispatching Requests������������������������������������������������������������������� 449 ■■Chapter 19: Dispatching Requests��������������������������������������������������������������������������������451 Preparing the Example Project��������������������������������������������������������������������������������������������������451 Creating the Model Class����������������������������������������������������������������������������������������������������������������������������������� 452 Creating the Web API Web Service�������������������������������������������������������������������������������������������������������������������� 452 Creating the MVC Controller and View��������������������������������������������������������������������������������������������������������������� 453 Testing the Example Application������������������������������������������������������������������������������������������������������������������������ 456 Understanding Request Dispatching�����������������������������������������������������������������������������������������457 Understanding the HttpServer Class����������������������������������������������������������������������������������������������������������������� 459 Understanding the HttpRoutingDispatcher Class���������������������������������������������������������������������������������������������� 460 Understanding the HttpControllerDispatcher Class������������������������������������������������������������������������������������������� 463 Customizing the Dispatch Process��������������������������������������������������������������������������������������������467 Creating Custom Message Handlers����������������������������������������������������������������������������������������������������������������� 468 Customizing Other Dispatch Components��������������������������������������������������������������������������������������������������������� 474 Summary�����������������������������������������������������������������������������������������������������������������������������������481 xvii www.it-ebooks.info ■ Contents ■■Chapter 20: URL Routing: Part I�������������������������������������������������������������������������������������483 Preparing the Example Project��������������������������������������������������������������������������������������������������483 Testing the Application Changes������������������������������������������������������������������������������������������������������������������������ 486 Understanding URL Routing �����������������������������������������������������������������������������������������������������486 Understanding the Routing Classes and Interfaces������������������������������������������������������������������������������������������� 488 Working with Convention-Based Routing����������������������������������������������������������������������������������492 Using Route Templates�������������������������������������������������������������������������������������������������������������������������������������� 493 Routing to the New Controller��������������������������������������������������������������������������������������������������������������������������� 494 Controlling Route Matching ������������������������������������������������������������������������������������������������������499 Using Routing Data Default Values�������������������������������������������������������������������������������������������������������������������� 500 Using Routing Constraints��������������������������������������������������������������������������������������������������������������������������������� 504 Summary�����������������������������������������������������������������������������������������������������������������������������������509 ■■Chapter 21: URL Routing: Part II������������������������������������������������������������������������������������511 Preparing the Example Project��������������������������������������������������������������������������������������������������511 Understanding Direct Routing���������������������������������������������������������������������������������������������������512 Creating a Direct Route������������������������������������������������������������������������������������������������������������������������������������� 513 Creating a Controller-wide Direct Route������������������������������������������������������������������������������������������������������������ 523 Customizing URL Routing����������������������������������������������������������������������������������������������������������525 Using a Route-Specific Message Handler��������������������������������������������������������������������������������������������������������� 525 Applying Custom Constraints to Direct Routes�������������������������������������������������������������������������������������������������� 529 Summary�����������������������������������������������������������������������������������������������������������������������������������533 ■■Chapter 22: Controllers and Actions������������������������������������������������������������������������������535 Preparing the Example Project��������������������������������������������������������������������������������������������������535 Understanding Controllers���������������������������������������������������������������������������������������������������������537 Creating a Controller������������������������������������������������������������������������������������������������������������������������������������������ 538 Using Built-in Services and Features���������������������������������������������������������������������������������������������������������������� 541 Understanding the ApiController Dispatch Process�������������������������������������������������������������������543 Preparing the Example Controller���������������������������������������������������������������������������������������������������������������������� 545 Understanding the Action Selection Process����������������������������������������������������������������������������������������������������� 547 xviii www.it-ebooks.info ■ Contents Understanding the RESTful/Non-RESTful Routing Problem������������������������������������������������������������������������������� 554 Understanding Filters���������������������������������������������������������������������������������������������������������������������������������������� 558 Understanding the Action Method Execution Process��������������������������������������������������������������������������������������� 559 Customizing the Controller Dispatch Process���������������������������������������������������������������������������559 Creating a Custom IHttpActionInvoker Implementation������������������������������������������������������������������������������������� 560 Creating a Custom IHttpActionSelector Implementation����������������������������������������������������������������������������������� 562 Creating a Controller-Specific Configuration ���������������������������������������������������������������������������������������������������� 563 Summary�����������������������������������������������������������������������������������������������������������������������������������565 ■■Chapter 23: Filters Part I�����������������������������������������������������������������������������������������������567 Preparing the Example Project��������������������������������������������������������������������������������������������������567 Understanding Filters����������������������������������������������������������������������������������������������������������������567 Working with Action Filters�������������������������������������������������������������������������������������������������������569 Creating an Action Filter by Implementing IActionFilter������������������������������������������������������������������������������������ 570 Using the Convenience Action Filter Base Class������������������������������������������������������������������������������������������������ 574 Creating a Short-Circuiting Action Filter������������������������������������������������������������������������������������������������������������ 577 Understanding the Filter Pipeline����������������������������������������������������������������������������������������������582 Displaying the Filter Pipeline����������������������������������������������������������������������������������������������������������������������������� 582 Understanding Filter Scope������������������������������������������������������������������������������������������������������������������������������� 584 Working with Authentication Filters������������������������������������������������������������������������������������������587 Preparing for Authentication������������������������������������������������������������������������������������������������������������������������������ 588 Understanding Authentication Filters���������������������������������������������������������������������������������������������������������������� 590 Creating an Authentication Filter����������������������������������������������������������������������������������������������������������������������� 591 Viewing the Filter Pipeline��������������������������������������������������������������������������������������������������������������������������������� 596 Summary�����������������������������������������������������������������������������������������������������������������������������������598 ■■Chapter 24: Filters Part II����������������������������������������������������������������������������������������������599 Preparing the Example Project��������������������������������������������������������������������������������������������������599 Reviewing Filters in the Dispatch Process �������������������������������������������������������������������������������599 Working with Authorization Filters��������������������������������������������������������������������������������������������600 Understanding Authorization Filters������������������������������������������������������������������������������������������������������������������ 601 Creating an Authorization Filter������������������������������������������������������������������������������������������������������������������������� 601 xix www.it-ebooks.info ■ Contents Appling the Authorization Filter ������������������������������������������������������������������������������������������������������������������������ 603 Removing the Authentication Filter������������������������������������������������������������������������������������������������������������������� 604 Using the Built-in Authorization Filter Attributes����������������������������������������������������������������������������������������������� 607 Reworking the Authentication Filter ����������������������������������������������������������������������������������������������������������������� 609 Working with Exception Filters��������������������������������������������������������������������������������������������������611 Understanding the Default Behavior ����������������������������������������������������������������������������������������������������������������� 611 Understanding Exception Filters ����������������������������������������������������������������������������������������������������������������������� 613 Creating an Exception Filter������������������������������������������������������������������������������������������������������������������������������ 614 Deriving the Filter from the ExceptionFilterAttribute Class������������������������������������������������������������������������������� 615 Working with Override Filters����������������������������������������������������������������������������������������������������617 Overriding Built-in Filter Types�������������������������������������������������������������������������������������������������������������������������� 618 Redefining Filter Policies����������������������������������������������������������������������������������������������������������������������������������� 620 Summary�����������������������������������������������������������������������������������������������������������������������������������621 ■■Chapter 25: Error Handling��������������������������������������������������������������������������������������������623 Preparing the Example Project��������������������������������������������������������������������������������������������������623 Dealing with Errors��������������������������������������������������������������������������������������������������������������������626 Relying on the Default Behavior ����������������������������������������������������������������������������������������������������������������������� 626 Using an Implementation of the IHttpActionResult Interface����������������������������������������������������������������������������� 629 Using the HttpError Class����������������������������������������������������������������������������������������������������������629 Using an Error Response and an HttpError Object��������������������������������������������������������������������������������������������� 630 Adding Extra Information to the HttpError Object���������������������������������������������������������������������������������������������� 632 Including Model State Errors in the HTTP Response����������������������������������������������������������������������������������������� 632 Controlling Error Detail�������������������������������������������������������������������������������������������������������������������������������������� 635 Displaying HttpError Information in the Client��������������������������������������������������������������������������������������������������� 636 Responding to Errors Globally ��������������������������������������������������������������������������������������������������637 Handling Exceptions������������������������������������������������������������������������������������������������������������������������������������������ 637 Logging Exceptions������������������������������������������������������������������������������������������������������������������������������������������� 641 Summary�����������������������������������������������������������������������������������������������������������������������������������644 xx www.it-ebooks.info ■ Contents ■■Chapter 26: Using OWIN�������������������������������������������������������������������������������������������������645 Understanding OWIN�����������������������������������������������������������������������������������������������������������������645 Creating a Self-hosted Web API Application������������������������������������������������������������������������������646 Creating the Project ������������������������������������������������������������������������������������������������������������������������������������������ 646 Installing the Packages������������������������������������������������������������������������������������������������������������������������������������� 646 Creating the Model and Repository������������������������������������������������������������������������������������������������������������������� 646 Defining the Configuration Classes������������������������������������������������������������������������������������������������������������������� 648 Creating the Web API Controller������������������������������������������������������������������������������������������������������������������������� 649 Testing the Self-hosted Web API Application ���������������������������������������������������������������������������������������������������� 650 Summary�����������������������������������������������������������������������������������������������������������������������������������650 Index���������������������������������������������������������������������������������������������������������������������������������651 xxi www.it-ebooks.info About the Author Adam Freeman is an experienced IT professional who has held senior positions in a range of companies, most recently serving as chief technology officer and chief operating officer of a global bank Now retired, he spends his time writing and running xxiii www.it-ebooks.info About the Technical Reviewer Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies He works at BluArancio SpA (www.bluarancio.com) as Senior Analyst/Developer and Microsoft Dynamics CRM Specialist He is a Microsoft Certified Solution Developer for NET, a Microsoft Certified Application Developer for NET, a Microsoft Certified Professional, and a prolific author and technical reviewer Over the past ten years, he’s written articles for Italian and international magazines and coauthored more than ten books on a variety of computer topics xxv www.it-ebooks.info [...]... 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 Figure 2- 7... menu Figure 2- 3 shows 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,... 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 Figure 2- 1 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 Figure 2- 2 Click the OK button, and Visual Studio... 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...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... with, the following URL:   http://localhost:37993 /api/ rsvp   Once you have entered the URL, click the Send button, and Postman will send a request to the web service and display the data that it gets, as shown in Figure 2- 8 Figure 2- 8.  Making a request using Postman 23 www.it-ebooks.info Chapter 2 ■ Your First Web API Application ■■Tip  Web API uses the ASP. NET routing system to match requests to controllers... method, change the HTTP verb for the request to POST by clicking the button marked GET to the right of the URL and selecting POST from the drop-down list Now click the x-www-form-urlencoded button to select the format in which Web API expects to receive form data and enter key/value pairs to define the properties in Table 2- 2 Table 2- 2.  The Key and Value Pairs for Testing the Web Service Key Value name... API 2 Controller – Empty from the list of controller types, as shown in Figure 2- 7 20 www.it-ebooks.info Chapter 2 ■ Your First Web API Application 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... 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... Summary In this chapter, I showed you how to use Web API to add an HTTP web service to an MVC framework application and consume that web service in the browser The example in this chapter is rather simple, but it does emphasize the fact that ASP. NET Web API is easy to work with and works happily alongside the MVC framework It also demonstrates that creating a web service is only part of the story You must

Ngày đăng: 06/06/2016, 15:05

Mục lục

  • Contents at a Glance

  • Contents

  • About the Author

  • About the Technical Reviewer

  • Part I: Getting Ready

    • Chapter 1: Getting Readys

      • What Do You Need to Know?

      • What Does Expert Mean?

      • What Is the Structure of This Book?

        • Part 1: Getting Ready

        • Part 2: Results and Parameters

        • Part 3: Dispatching Requests

        • Are There Lots of Examples?

        • Where Can You Get the Example Code?

        • How Do You Set Up a Development Environment?

          • Getting Visual Studio

            • Preparing Visual Studio

            • Getting Google Chrome

              • Selecting Chrome for Debugging

              • Summary

              • Chapter 2: Your First Web API Application

                • Preparing the Example Project

                  • Creating the Visual Studio Project

                  • Adding and Updating NuGet Packages

                  • Setting the Port and Start URL

                  • Creating the MVC Application

                    • Creating the Model

                    • Creating the MVC Controller

                    • Creating the Views

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan