asp.net web api essentials using c# - itcourseware web api essentials using c# evaluation ... what...

36
Object Innovations Course 4147 Student Guide Revision 4.6 ASP.NET Web API Essentials Using C# EVALUATION COPY

Upload: buiminh

Post on 29-Jun-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Object Innovations Course 4147

Student Guide Revision 4.6

ASP.NET Web API Essentials Using C#

EVALUATION COPY

Page 2: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC ii All Rights Reserved

ASP.NET Web API Essentials Using C# Rev. 4.6 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners.

™ is a trademark of Object Innovations. Author: Robert J. Oberg Copyright ©2014 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

EVALUATION COPY

Page 3: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 Introduction to ASP.NET Web API Chapter 2 Web API and HTTP Chapter 3 Media Formatters and Content Negotiation Chapter 4 JavaScript Clients Chapter 5 Binding, Validation and Routing Chapter 6 .NET Clients Appendix A Learning Resources

EVALUATION COPY

Page 4: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• The course software installs to the root directory C:\OIC\WebApiCs.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The Demos directory is provided for doing in-class demonstrations led by the instructor.

EVALUATION COPY

Page 5: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1: Introduction to ASP.NET Web API ................................................................ 1 ASP.NET Web API ............................................................................................................ 3 REST................................................................................................................................... 4 Representation, State and Transfer ..................................................................................... 5 Collections and Elements.................................................................................................... 6 Web API Demo................................................................................................................... 7 Specifying a Start Page ..................................................................................................... 11 Implementing PUT Verb................................................................................................... 12 Using Fiddler .................................................................................................................... 13 Composing a Request ....................................................................................................... 15 ASP.NET MVC and Web API.......................................................................................... 17 String API Demo............................................................................................................... 18 Route Registration ............................................................................................................ 20 Lab 1 ................................................................................................................................. 23 Summary ........................................................................................................................... 24

Chapter 2: Web API and HTTP........................................................................................ 29 HTTP Response Codes ..................................................................................................... 31 POST Response Code ....................................................................................................... 32 HttpResponseException.................................................................................................... 33 Performing CRUD Operations.......................................................................................... 34 Books API Example.......................................................................................................... 35 Server Code: Model .......................................................................................................... 36 Book Repository ............................................................................................................... 37 BooksController................................................................................................................ 39 Exercise the Server Using Fiddler .................................................................................... 41 Exercise PUT .................................................................................................................... 42 Exercise POST.................................................................................................................. 43 Exercise GET Again ......................................................................................................... 44 Lab 2 ................................................................................................................................. 45 Summary ........................................................................................................................... 46

Chapter 3: Media Formatters and Content Negotiation................................................. 55 Internet Media Types ........................................................................................................ 57 Media Type in HTTP........................................................................................................ 58 Media Type Demo ............................................................................................................ 59 MediaFmtDemo Code....................................................................................................... 62 Exercising PUT................................................................................................................. 63 Exercising POST............................................................................................................... 64 HTTP Content Negotiation............................................................................................... 65 Media Range and Quality Factors .................................................................................... 66 Web API Content Negotiation .......................................................................................... 67 Default Content Negotiator............................................................................................... 68

EVALUATION COPY

Page 6: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC vi All Rights Reserved

Media Type Mappings ...................................................................................................... 69 Query String Mapping ...................................................................................................... 70 Request Header Mapping.................................................................................................. 71 Content Negotiation Priority............................................................................................. 72 Info about Media Type Formatters ................................................................................... 73 Serialization ...................................................................................................................... 74 Serialization in .NET ........................................................................................................ 75 JavaScript Object Notation ............................................................................................... 76 JSON Data Types.............................................................................................................. 77 Comparing JSON and XML ............................................................................................. 78 XML Serialization ............................................................................................................ 79 BSON................................................................................................................................ 80 Lab 3 ................................................................................................................................. 81 Summary ........................................................................................................................... 82

Chapter 4: JavaScript Clients ........................................................................................... 91 What is DHTML? ............................................................................................................. 93 DHTML Components ....................................................................................................... 94 Document Object Model................................................................................................... 95 Browser Objects................................................................................................................ 96 Accessing DOM Nodes..................................................................................................... 97 Demo: Using the DOM..................................................................................................... 98 Using jQuery................................................................................................................... 101 CSS (Cascading Style Sheets) ........................................................................................ 103 CSS Syntax ..................................................................................................................... 104 Style Sheets..................................................................................................................... 105 jQuery Library ................................................................................................................ 107 jQuery and Visual Studio................................................................................................ 108 Selectors.......................................................................................................................... 109 jQuery Wrapper .............................................................................................................. 110 Selector and Wrapper Example ...................................................................................... 111 Example Script................................................................................................................ 112 jQuery Ajax Methods...................................................................................................... 114 Shorthand Methods ......................................................................................................... 115 jQueryHouses Example .................................................................................................. 116 Using getJSON()............................................................................................................. 117 Handling Errors............................................................................................................... 118 Low Level Interface........................................................................................................ 119 HouseDemo Example ..................................................................................................... 120 Invoking POST ............................................................................................................... 121 Lab 4 ............................................................................................................................... 122 Summary ......................................................................................................................... 123

Chapter 5: Binding, Validation and Routing ................................................................. 127 Binding Data from HTTP Requests................................................................................ 129 Reading a Raw HTTP Request ....................................................................................... 130

EVALUATION COPY

Page 7: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC vii All Rights Reserved

House Controller............................................................................................................. 131 Deserializing JSON......................................................................................................... 132 Client JavaScript Code.................................................................................................... 133 Reading HTTP Request into CLR .................................................................................. 134 Binding in ASP.NET Web API ...................................................................................... 135 Bind HTTP Request to Simple Types............................................................................. 136 Binding via Route Data................................................................................................... 137 Binding via Query String................................................................................................ 138 JavaScript Client ............................................................................................................. 139 Binding via Request Body .............................................................................................. 140 Client Code for Using Request Body ............................................................................. 141 Bind HTTP Request to Complex Type........................................................................... 142 Simple and Complex Types ............................................................................................ 143 Client Code for POST Request ....................................................................................... 144 Client Code for GET Request ......................................................................................... 145 Validation in Web API.................................................................................................... 146 Web API Validation Example ........................................................................................ 147 Validation Rules ............................................................................................................. 148 Running the Example...................................................................................................... 149 Controller Code............................................................................................................... 151 Lab 5A ............................................................................................................................ 152 ASP.NET Routing........................................................................................................... 153 Routing in ASP.NET Web API ...................................................................................... 154 Simple Route Example ................................................................................................... 155 Running the Example...................................................................................................... 156 Default Route Map.......................................................................................................... 157 Matching URLs to Route ................................................................................................ 158 Lab 5B............................................................................................................................. 159 Summary ......................................................................................................................... 160

Chapter 6: .NET Clients................................................................................................... 169 Web API Clients ............................................................................................................. 171 HttpClient........................................................................................................................ 172 Initializing HttpClient ..................................................................................................... 173 Issuing a GET Request ................................................................................................... 174 Issuing a POST Request ................................................................................................. 175 Web API Client Library Demo....................................................................................... 176 Adding a House............................................................................................................... 179 Update ............................................................................................................................. 181 Delete .............................................................................................................................. 182 Lab 6 ............................................................................................................................... 183 Summary ......................................................................................................................... 184

Appendix A Learning Resources................................................................................... 191

EVALUATION COPY

Page 8: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC viii All Rights Reserved

EVALUATION COPY

Page 9: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Introduction to ASP.NET Web API

EVALUATION COPY

Page 10: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 2 All Rights Reserved

Introduction to ASP.NET Web API

Objectives

After completing this unit you will be able to:

• Explain what ASP.NET Web API is and why it is useful.

• Describe RESTful Web services, which can be created using Web API

• Implement HTTP services using Web API with and without using ASP.NET MVC.

• Use Fiddler to exercise HTTP requests while developing a Web API service

EVALUATION COPY

Page 11: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 3 All Rights Reserved

ASP.NET Web API

• ASP.NET Web API is a framework for building and consuming HTTP services.

• It is built into ASP.NET and can be used by both Web Forms and MVC applications, as well as used standalone.

• Relying on standard HTTP, Web API facilitates creating services that can reach a wide variety of devices.

• Visual Studio 2013 provides templates that facilitate creating Web API services.

• Web API does not dictate a particular architectural style, but it is a great platform for implementing RESTful Web services.

EVALUATION COPY

Page 12: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 4 All Rights Reserved

REST

• REST (Representational State Transfer) is an architectural style for designing distributed systems.

− It is based on the architectural style of the Web.

− It is not a protocol, like SOAP is.

• Key features of Web architecture include:

− Addressable resources specified by a URI (uniform resource identifier)

− Standard resource formats such as HTML, XML, JSON, MIME, etc.

− A uniform interface (HTTP) for interacting with these resources

− Statelessness in interactions between clients and services

• A RESTful Web service has a very simple structure.

− A request is made through a URI.

− A response is a message in a standard format, often XML.

EVALUATION COPY

Page 13: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 5 All Rights Reserved

Representation, State and Transfer

• A resource is any entity that can be addressed (by a URI) on the Web.

• A representation is typically a document, such as an XML document, that represents the resource.

• When it receives a representation, a client application is in a state and will enter a new state when it traverses a hyperlink.

• The client application transfers state with each resource representation: “representational state transfer”.

• The concept of REST was developed by Roy Fielding1 in his Ph. D. dissertation. Here is Dr. Fielding’s explanation2 of “representation state transfer”:

− "Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use."

1 Roy Fielding is one of the principal architects of the Web standards of HTTP and URI, and he co-founded the Apache HTTP Server project. 2 Quoted in “Building Web Services the REST Way” by Roger Costello (http://www.xfront.com/REST-Web-Services.html).

EVALUATION COPY

Page 14: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 6 All Rights Reserved

Collections and Elements

• A resource is typically a collection or an element in the collection.

• A resource is retrieved using the HTTP GET verb.

− Collection:

GET http://example.com/resources

− Element in collection:

GET http://example.com/resources/101

• A new element is created in a collection by using the POST verb.

− A representation of the new element is passed in the body of the POST request.

• An element in a collection is updated by using the PUT verb.

− A representation of the updated element is passed in the body of the PUT request.

• An element is removed from a collection by using the DELETE verb.

EVALUATION COPY

Page 15: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 7 All Rights Reserved

Web API Demo

• To get started with Web API, let’s create a simple demo.

− To illustrate a minimal application, we will start with an empty ASP.NET project and only get the folders and core references for Web API, not using MVC.

1. Create in the Demos directory a new empty ASP.NET Web Application called WebApiDemo.

2. In the second screen, choose the Empty template and add folders and core references for Web API. Click OK.

EVALUATION COPY

Page 16: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 8 All Rights Reserved

Web API Demo (Cont’d)

3. Examine the files and folders in the new project.

4. Delete the folders App_Data, App_Start, Controllers and Models. Delete the file Global.asax.

5. Add a new class DemoController to your new project.

6. Make it derive from ApiController, which will require you to import System.Web.Http.

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; namespace WebApiDemo { public class DemoController : ApiController { } }

EVALUATION COPY

Page 17: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 9 All Rights Reserved

Web API Demo (Cont’d)

7. Declare a private static variable message initialized in a static constructor.

public class DemoController : ApiController { private static string message; static DemoController() { message = "Hello Web API"; } } 8. Implement a public method Get() that returns message.

public string Get() { return message; } 9. Add a Global Application Class. In the Application_Start()

method provide code to add a route to the configuration.

protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configuration.Routes.Add( "Default", new HttpRoute("api/{controller}")); } 10. You will need to import the namespaces System.Web.Http

and System.Web.Http.Routing,

11. Build and run. You will get an HTTP 403 “Forbidden” error.

EVALUATION COPY

Page 18: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 10 All Rights Reserved

Web API Demo (Cont’d)

12. Append api/demo to the URI (not case sensitive), which will look like this (port number varies):

http://localhost:51168/api/demo 13. Click Save in the dialog that comes up. 3

14. Examine the file demo.json that you downloaded. You can use Notepad. (You could also have clicked Open and selected Notepad from a list of programs.)

15. You will now see the message displayed in Notepad.

3 This demo assumes you are using Internet Explorer. Other browsers will exhibit different behavior. For example, Firefox will return XML rather than JSON. This chapter illustrates IE. You can use another browser, but you will need to allow for the browser’s different behavior.

EVALUATION COPY

Page 19: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 11 All Rights Reserved

Specifying a Start Page

• We can make it a little easier to run this example by specifying a start page in the project properties.

− Choose Specific Page for Start Action with api/demo as the address.

• Now when you run the program you don’t get an error message at first but immediately have useful output.

− The 9 bytes here represent our having changed the message

to “Goodbye” via a PUT verb. Stay tuned!

EVALUATION COPY

Page 20: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 12 All Rights Reserved

Implementing PUT Verb

• Web API uses convention to associate controller actions with HTTP verbs.

− Get corresponds to GET, Post corresponds to POST and so on.

• To indicate that an input parameter in a controller action comes from the body of an HTTP request, use the [FromBody] attribute.

• Here is code for a Put() method that will change the message to be delivered.

public void Put([FromBody]string value) { message = value; }

EVALUATION COPY

Page 21: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 13 All Rights Reserved

Using Fiddler

• Fiddler is an invaluable tool in working with HTTP.

− You can see requests and responses in a variety of formats.

− You can compose requests to test your operations.

− In particular, you can test POST, PUT and DELETE.

• If Fiddler is not already installed on your system, download it from here (choose Fiddler 4):

http://www.fiddler2.com/fiddler2/

• Bring up Fiddler4 and start recording HTTP traffic.

4 For convenience you may wish to pin Fiddler to your Start menu.

EVALUATION COPY

Page 22: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 14 All Rights Reserved

Using Fiddler (Cont’d)

• In the Web Sessions pane on the left, double-click on the session you wish to examine. Make sure the “Inspectors” tab is selected.

− The request is shown on top-right pane.

− The response is shown on bottom-right pane.

• There are various formats you can choose for viewing request and response.

− Here is the response in Raw format, showing both the header and the body of the response.

HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?QzpcT0lDXE12Y0NzXERlbw... X-Powered-By: ASP.NET Date: Tue, 19 Mar 2013 17:36:28 GMT Content-Length: 15 "Hello Web API"

EVALUATION COPY

Page 23: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 15 All Rights Reserved

Composing a Request

• We can test the PUT verb by selecting the “Composer” tab in the Request pane.

− To get starter HTTP, drag the GET request we used from the Web Sessions pane.

− Select the PUT verb from the dropdown.

− Add specification of Content-Type to the Request Headers, since there will be a body to a PUT request.

Accept: image/jpeg, application/x-ms-application,.. Accept-Language: en-US Content-Type: application/json User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; ... Accept-Encoding: gzip, deflate Connection: Keep-Alive Host: localhost:52827

− In the Request Body, enter a quoted string for the desired message.

"Goodbye"

EVALUATION COPY

Page 24: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 16 All Rights Reserved

Composing a Request (Cont’d)

− Click the Execute button. You should receive an HTTP 204 (No Content) response code.

− To view the results of the operation, perform a GET again. Drag the original GET into the Composer window. Here is the response in WebView.

EVALUATION COPY

Page 25: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 17 All Rights Reserved

ASP.NET MVC and Web API

• ASP.NET provides a useful template for creating HTTP services with Web API.

− Notice that folders and core references for both MVC5 and Web API are automatically provided.

• We illustrate by creating a simple API to maintain a list of strings.

− The completed demo is in MvcStringApi\Step1 in the chapter folder.

5 Don’t worry if you are not familiar with MVC. We use the template that works with MVC as well as Web API purely for the convenience of being able to look at some sample code that is automatically generated. We also make use of a simple view to provide a documentation page.

EVALUATION COPY

Page 26: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 18 All Rights Reserved

String API Demo

1. Create a new ASP.NET Web Application MvcStringApi using the Web API template.

2. Examine the starter code, beginning with the ValuesController class (in the Controllers folder).

public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } }

EVALUATION COPY

Page 27: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 19 All Rights Reserved

String API Demo (Cont’d)

3. Build and run, supplying this relative URI as the Specific Page for Start Action in the project properties:

api/values 4. Examine the output in Notepad.

5. If you desire, you can perform more experiments using Fiddler.

6. Examine the routing code, which is called from Global.asax.cs.

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register( GlobalConfiguration.Configuration); ... }

EVALUATION COPY

Page 28: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 20 All Rights Reserved

Route Registration

• Examine WebApiConfig.cs in the App_Start folder. public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }

− The default route template has an optional id parameter.

− Also, the route is added using the MapHttpRoute() extension method.

EVALUATION COPY

Page 29: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 21 All Rights Reserved

String API Demo (Cont’d)

7. Add a new controller. Use the Web API 2 – Empty controller as the template in the scaffolding options.

8. Call your new controller StringsController.

EVALUATION COPY

Page 30: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 22 All Rights Reserved

String API Demo (Cont’d)

9. Provide code to define a static data member info of type List<string>, initialized in a static constructor.

public class StringsController : ApiController { private static List<string> info = new List<string>(); static StringsController() { info.Add("alpha"); info.Add("beta"); info.Add("gamma"); } } 10. Provide the following code to implement a Get() method.

// GET api/strings public IEnumerable<string> Get() { return info; } 11. Specify api/strings as the Start Action.

12. Build and run. Examine the output in Notepad.

13. This completes the demo. You will finish implementing the example in the lab.

EVALUATION COPY

Page 31: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 23 All Rights Reserved

Lab 1

Implementing and Testing a String API

In this lab you will finish the example we started to implement a string API that manages a list of strings. You will be able to retrieve an individual string, add a new string, update a string and delete a string. You will use Fiddler for testing.

Detailed instructions are contained in the Lab 1 write-up at the end of the chapter.

Suggested time: 30 minutes

EVALUATION COPY

Page 32: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 24 All Rights Reserved

Summary

• ASP.NET Web API is a framework for building and consuming HTTP services.

• REST (Representational State Transfer) is an architectural style for designing distributed systems.

• Web API does not dictate a particular architectural style, but it is a great platform for implementing RESTful Web services.

• You can implement HTTP services using Web API with and without using ASP.NET MVC.

• You can use Fiddler to exercise HTTP requests while developing a Web API service

EVALUATION COPY

Page 33: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 25 All Rights Reserved

Lab 1

Implementing and Testing a String API

Introduction In this lab you will finish the example we started to implement a string API that manages a list of strings. You will be able to retrieve an individual string, add a new string, update a string and delete a string. You will use Fiddler for testing. Suggested Time: 30 minutes Root Directory: C:\OIC\WebApiCs Directories: Labs\Lab1 (do your work here) Chap01\MvcStringApi\Step1 (starter code) Chap01\MvcStringApi\Step2 (solution) Instructions 1. Build and run the starter code. It’s what we created in the demo, except we replaced

the home page with a simple page documenting the operations that can be performed in the browser.

2. Provide the following code to retrieve an individual string at a specified index position in the list. Make use of the id parameter.

// GET api/strings/5 public string Get(int id) { return info[id]; } 3. Build and run. Try out the following relative URI:

EVALUATION COPY

Page 34: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 26 All Rights Reserved

api/strings/1 4. Examine the output in Notepad.

5. Provide the following code to add a new string to the list.

// POST api/strings public void Post([FromBody]string value) { info.Add(value); } 6. Build and run. Start Fiddler. Exercise a GET request, and view the response in

Fiddler in JSON format.

7. Open the Composer and drag the GET request from the Web Sessions window to the Composer’s window. Execute this request and verify you get the same response.

8. Edit the Request Headers to add a Content-Type of application/json.

Accept: image/jpeg, application/x-ms-application, image/gif... Accept-Language: en-US Content-Type: application/json User-Agent: Mozilla/4.0 (compatible; MSIE 7.0;... 9. Change the verb to POST. The window for the Request Body will now be enabled.

Enter the quoted string “delta”.

EVALUATION COPY

Page 35: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 27 All Rights Reserved

10. Execute. Perform a GET request again and examine the response in JSON format.

11. Terminate the application. Provide code to implement PUT.

// PUT api/strings/5 public void Put(int id, [FromBody]string value) { info[id] = value; }

EVALUATION COPY

Page 36: ASP.NET Web API Essentials Using C# - ITCourseware Web API Essentials Using C# EVALUATION ... What is DHTML? ... Document Object Model

WebApiCs Chapter 1

Rev. 4.6 Copyright © 2014 Object Innovations Enterprises, LLC 28 All Rights Reserved

12. Build and run. Use Fiddler to exercise PUT with an index of 1 and a new string “beetle”.

13. Execute a GET request and examine the response in JSON format.

14. Terminate the application. Provide code to implement DELETE.

// DELETE api/strings/5 public void Delete(int id) { info.RemoveAt(id); } 15. Use Fiddler to test deleting the string at index 1. The list should now consist of

“alpha”, “gamma” and “delta”. You’re done!

EVALUATION COPY