or COPY ASP.NET MVC USING C# - ITCourseware...Chapter 1 Introduction to ASP.NET MVC Chapter 2...

of 68 /68
EVALUATION COPY ASP.NET MVC USING C# Unauthorized Reproduction or Distribution Prohibited

Embed Size (px)

Transcript of or COPY ASP.NET MVC USING C# - ITCourseware...Chapter 1 Introduction to ASP.NET MVC Chapter 2...

  • EVALUATION COPY ASP.NET MVC

    USING C#

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    Object Innovations Course 4143

    Student Guide Revision 4.7

    ASP.NET MVC Using C#

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC ii All Rights Reserved

    ASP.NET MVC Using C# Rev. 4.7 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. Authors: Robert Hurlbut and Robert J. Oberg Copyright ©2015 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC iii All Rights Reserved

    Table of Contents (Overview) Chapter 1 Introduction to ASP.NET MVC Chapter 2 Getting Started with ASP.NET MVC Chapter 3 ASP.NET MVC Architecture Chapter 4 The Model Chapter 5 The Controller Chapter 6 The View Chapter 7 Routing Chapter 8 Unit Testing Chapter 9 Security Chapter 10 Combining ASP.NET MVC and Web Forms Chapter 11 ASP.NET Web API Chapter 12 ASP.NET and Azure Appendix A Learning Resources Appendix B Deployment in IIS 7.5

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC iv All Rights Reserved

    Directory Structure

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

    Example programs for each chapter are in named subdirectories of chapter directories Chap02, Chap03, 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.

    Data files install to the directory C:\OIC\Data.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC v All Rights Reserved

    Table of Contents (Detailed)

    Chapter 1: Introduction to ASP.NET MVC....................................................................... 1 Review of ASP.NET Web Forms ....................................................................................... 3 Advantages of ASP.NET Web Forms ................................................................................ 4 Disadvantages of ASP.NET Web Forms ............................................................................ 5 Model-View-Controller Pattern.......................................................................................... 6 ASP.NET MVC .................................................................................................................. 7 Advantages of ASP.NET MVC .......................................................................................... 8 Disadvantages of ASP.NET MVC...................................................................................... 9 Goals of ASP.NET MVC.................................................................................................. 10 Unit Testing ...................................................................................................................... 11 Summary ........................................................................................................................... 12

    Chapter 2: Getting Started with ASP.NET MVC............................................................ 13 An ASP.NET MVC 5 Testbed.......................................................................................... 15 Visual Studio ASP.NET MVC Demo............................................................................... 16 Starter Application............................................................................................................ 18 Simple App with Controller Only..................................................................................... 20 Action Methods and Routing............................................................................................ 26 Action Method Return Type ............................................................................................. 27 Rendering a View ............................................................................................................. 28 Creating a View in Visual Studio ..................................................................................... 29 The View Web Page ......................................................................................................... 30 Dynamic Output................................................................................................................ 31 Razor View Engine ........................................................................................................... 32 Embedded Scripts ............................................................................................................. 33 Embedded Script Example................................................................................................ 34 Using a Model with ViewBag .......................................................................................... 35 Controller Using Model and ViewBag ............................................................................. 36 View Using Model and ViewBag..................................................................................... 37 Using Model Directly ....................................................................................................... 38 A View Using Model in Visual Studio............................................................................. 39 View Created by Visual Studio ........................................................................................ 40 Passing Parameters in Query String.................................................................................. 41 Lab 2 ................................................................................................................................. 42 Summary ........................................................................................................................... 43

    Chapter 3: ASP.NET MVC Architecture......................................................................... 51 The Controller in ASP.NET MVC.................................................................................... 53 The View in ASP.NET MVC ........................................................................................... 54 The Model in ASP.NET MVC.......................................................................................... 55 How MVC Works ............................................................................................................. 56 Using Forms...................................................................................................................... 57 HTML Helper Functions .................................................................................................. 58

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC vi All Rights Reserved

    Handling Form Submission .............................................................................................. 59 Model Binding .................................................................................................................. 60 Greet View........................................................................................................................ 61 Input Validation ................................................................................................................ 62 Nullable Type ................................................................................................................... 63 Checking Model Validity.................................................................................................. 64 Validation Summary ......................................................................................................... 65 Lab 3 ................................................................................................................................. 66 Summary ........................................................................................................................... 67

    Chapter 4: The Model ........................................................................................................ 75 Microsoft Technologies for the Model ............................................................................. 77 SmallPub Database ........................................................................................................... 78 ADO.NET ......................................................................................................................... 80 Language Integrated Query (LINQ) ................................................................................. 81 ADO.NET Entity Framework........................................................................................... 82 EDM Example .................................................................................................................. 83 SmallPub Tables ............................................................................................................... 86 SmallPub Entity Data Model ............................................................................................ 87 Entity Data Model Concepts............................................................................................. 88 Querying the EDM............................................................................................................ 89 Class Diagram................................................................................................................... 90 Context Class .................................................................................................................... 91 List of Categories.............................................................................................................. 92 List of Books..................................................................................................................... 94 LINQ to Entities Demo..................................................................................................... 96 A LINQ Query .................................................................................................................. 97 IntelliSense........................................................................................................................ 98 Controller .......................................................................................................................... 99 Using a Parameter ........................................................................................................... 100 Modifying a Data Source ................................................................................................ 101 LINQ to Entities Insert Example .................................................................................... 103 LINQ to Entities Delete Example ................................................................................... 104 Entity Framework in a Class Library.............................................................................. 105 Data Access Class Library.............................................................................................. 106 Client Code ..................................................................................................................... 107 Configuration in Entity Framework 6............................................................................. 108 ASP.NET MVC Database Clients .................................................................................. 109 ASP.NET MVC CRUD Demo........................................................................................ 110 Lab 4 ............................................................................................................................... 115 NuGet Package Manager ................................................................................................ 116 Visual Studio Extensions ................................................................................................ 117 Online Gallery................................................................................................................. 118 Entity Framework 6 via NuGet....................................................................................... 119 Summary ......................................................................................................................... 120

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC vii All Rights Reserved

    Chapter 5: The Controller ............................................................................................... 127 IController Interface ....................................................................................................... 129 A Low Level Controller.................................................................................................. 130 Displaying Context ......................................................................................................... 131 Add and Subtract ............................................................................................................ 132 Controller Base Class...................................................................................................... 133 Controller Base Class...................................................................................................... 134 Action Methods............................................................................................................... 135 Action Method Example ................................................................................................. 136 HomeController .............................................................................................................. 137 MathController................................................................................................................ 138 Invoking MathController ................................................................................................ 139 Receiving Input............................................................................................................... 140 Binding Example ............................................................................................................ 141 Non-Nullable Parameters................................................................................................ 142 Nullable Parameters ........................................................................................................ 143 Using a Model................................................................................................................. 144 Action Results................................................................................................................. 145 Action Result Example ................................................................................................... 146 Output Demo................................................................................................................... 147 JavaScript Object Notation ............................................................................................. 150 Action Method Attributes ............................................................................................... 151 HTML Output ................................................................................................................. 152 Filters .............................................................................................................................. 153 Asynchronous Controllers .............................................................................................. 155 Lab 5 ............................................................................................................................... 156 Summary ......................................................................................................................... 157

    Chapter 6: The View......................................................................................................... 165 View Responsibility........................................................................................................ 167 A Program without a View ............................................................................................. 168 A Program with a View .................................................................................................. 169 View Page ....................................................................................................................... 170 Passing Data to the View ................................................................................................ 171 Dynamic and ExpandoObject ......................................................................................... 172 Passing Lists to the View................................................................................................ 173 HTML Helper Methods .................................................................................................. 174 Link-Building Helpers .................................................................................................... 175 Form Helpers .................................................................................................................. 176 Html Helper Example ..................................................................................................... 177 Validation Helpers .......................................................................................................... 179 Templated Helpers .......................................................................................................... 180 Validation in Model ........................................................................................................ 182 Validation in Controller .................................................................................................. 183 ValidationMessage Helper.............................................................................................. 184 Running the Example...................................................................................................... 185

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC viii All Rights Reserved

    Lab 6 ............................................................................................................................... 186 Summary ......................................................................................................................... 187

    Chapter 7: Routing ........................................................................................................... 195 ASP.NET Routing........................................................................................................... 197 Routing in ASP.NET MVC ............................................................................................ 198 RouteCollectionExtensions Class ................................................................................... 199 Simple Route Example ................................................................................................... 200 Default Values for URL Parameters ............................................................................... 202 Using a Default Route..................................................................................................... 203 Home Controller ............................................................................................................. 204 Assigning Parameter Values ........................................................................................... 205 Controller Code............................................................................................................... 206 View Code ...................................................................................................................... 207 Running the Example...................................................................................................... 208 Properties of Routes........................................................................................................ 209 UrlParameter.Optional .................................................................................................... 210 Matching URLs to Route ................................................................................................ 211 Demo: Route Order......................................................................................................... 212 Install Route Debugging Utility...................................................................................... 216 Multiple Matches ............................................................................................................ 218 Fixing the Bug ................................................................................................................ 219 Debugging Routes: Summary ......................................................................................... 220 Areas ............................................................................................................................... 221 Demo: Areas ................................................................................................................... 222 Summary ......................................................................................................................... 225

    Chapter 8: Unit Testing.................................................................................................... 227 Test-Driven Development............................................................................................... 229 Functional Tests .............................................................................................................. 230 Unit Tests ........................................................................................................................ 231 Test Automation.............................................................................................................. 232 Refactoring...................................................................................................................... 233 Regression Testing.......................................................................................................... 234 Unit Testing in ASP.NET MVC ..................................................................................... 235 Creating a Test Project.................................................................................................... 236 Adding a Unit Test Project ............................................................................................. 237 MVC Unit Test Example ................................................................................................ 238 A Test Class Library ....................................................................................................... 239 The Model....................................................................................................................... 240 Testing the Model ........................................................................................................... 241 Structure of Unit Tests .................................................................................................... 242 Assertions........................................................................................................................ 243 Visual Studio Unit Framework ....................................................................................... 244 Assert Class..................................................................................................................... 245 Assert.AreEqual() ........................................................................................................... 246

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC ix All Rights Reserved

    More Assert Methods...................................................................................................... 247 CollectionAssert Class.................................................................................................... 248 StringAssert Class........................................................................................................... 249 Test Case......................................................................................................................... 250 Test Methods................................................................................................................... 251 Test Class ........................................................................................................................ 252 Test Runner..................................................................................................................... 253 More Tests ...................................................................................................................... 254 Ignoring Tests ................................................................................................................. 255 Fixing the Bug ................................................................................................................ 256 Testing Controllers ......................................................................................................... 257 Lab 8A ............................................................................................................................ 258 Classes with External Dependencies .............................................................................. 259 Dependency Injection ..................................................................................................... 260 Mocking Frameworks ..................................................................................................... 261 Using Moq ...................................................................................................................... 262 Installing Moq Using NuGet........................................................................................... 263 MvcMortgage Example .................................................................................................. 264 Models ............................................................................................................................ 265 Controller ........................................................................................................................ 266 Index View...................................................................................................................... 267 Monthly Payment View .................................................................................................. 268 Unit Tests ........................................................................................................................ 269 Inversion of Control (IoC) Containers............................................................................ 270 Lab 8B............................................................................................................................. 271 Summary ......................................................................................................................... 272

    Chapter 9: Security........................................................................................................... 285 Web Security................................................................................................................... 287 Input Forgery .................................................................................................................. 288 Cross-Site Scripting ........................................................................................................ 290 Cross-Site Scripting Example......................................................................................... 292 XSS Example .................................................................................................................. 293 Entering JavaScript ......................................................................................................... 295 The Attack....................................................................................................................... 296 What Allowed the Attack................................................................................................ 297 Blocking the Attack ........................................................................................................ 298 Using Razor .................................................................................................................... 299 Session Hijacking ........................................................................................................... 300 Cross-Site Request Forgery ............................................................................................ 302 XSRF Example ............................................................................................................... 304 Controller and Model Code ............................................................................................ 306 View Code ...................................................................................................................... 307 Attacker Code ................................................................................................................. 308 The Defense .................................................................................................................... 309 SQL Injection.................................................................................................................. 310

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC x All Rights Reserved

    Using the MVC Framework Securely............................................................................. 314 Authorize Attribute ......................................................................................................... 315 ChildActionOnly Attribute ............................................................................................. 316 RequireHttps Attribute.................................................................................................... 317 ValidateInput Attribute ................................................................................................... 318 Summary ......................................................................................................................... 319

    Chapter 10: Combining ASP.NET MVC and Web Forms ........................................... 321 Using Web Forms in an MVC Application .................................................................... 323 Linking and Redirecting from Web Forms Pages to MVC Actions............................... 324 Default.aspx .................................................................................................................... 325 Web Forms in MVC Example ........................................................................................ 326 Sharing Data between ASP.NET MVC and ASP.NET Web Forms .............................. 328 Using Web Form Controls in MVC Views..................................................................... 329 Using MVC in a Web Forms Application ...................................................................... 330 Steps to Create Hybrid MVC - Web Forms Application................................................ 331 Web Forms MVC Interop in VS 2015............................................................................ 333 Summary ......................................................................................................................... 334

    Chapter 11: ASP.NET Web API ..................................................................................... 335 ASP.NET Web API ........................................................................................................ 337 REST............................................................................................................................... 338 Representation, State and Transfer ................................................................................. 339 Collections and Elements................................................................................................ 340 Web API Demo............................................................................................................... 341 Specifying a Start Page ................................................................................................... 345 Implementing PUT Verb................................................................................................. 346 Using Fiddler .................................................................................................................. 347 Composing a Request ..................................................................................................... 349 ASP.NET MVC and Web API........................................................................................ 351 String API Demo............................................................................................................. 352 Route Registration .......................................................................................................... 354 Lab 11A .......................................................................................................................... 357 HTTP Response Codes ................................................................................................... 358 POST Response Code ..................................................................................................... 359 HttpResponseException.................................................................................................. 360 Web API Clients ............................................................................................................. 361 HttpClient........................................................................................................................ 362 Initializing HttpClient ..................................................................................................... 363 Issuing a GET Request ................................................................................................... 364 Issuing a POST Request ................................................................................................. 365 Lab 11B........................................................................................................................... 366 Summary ......................................................................................................................... 367

    Chapter 12: ASP.NET and Azure ................................................................................... 377 What Is Windows Azure? ............................................................................................... 379 A Windows Azure Testbed............................................................................................. 380

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC xi All Rights Reserved

    Windows Azure Demo.................................................................................................... 381 Publish to Azure.............................................................................................................. 382 Add an Account .............................................................................................................. 383 Select Existing Web App................................................................................................ 384 Create a Web App........................................................................................................... 385 Publish Windows Azure Web......................................................................................... 386 Web Deployment Completed.......................................................................................... 388 Modifying a Web Application ........................................................................................ 389 Deploy to Original Site ................................................................................................... 390 Publish Preview .............................................................................................................. 391 Lab 12 ............................................................................................................................. 392 Summary ......................................................................................................................... 393

    Appendix A: Learning Resources.................................................................................... 397

    Appendix B: Deployment in IIS 7.5 ................................................................................ 401 Internet Information Services ......................................................................................... 402 Installing IIS 7.5 ............................................................................................................. 403 MVC with IIS 7.5 ........................................................................................................... 404 .NET Framework Version............................................................................................... 405 Registering ASP.NET..................................................................................................... 408 Demo: Running an MVC App on IIS ............................................................................. 409 Convert to an Application............................................................................................... 410 XCOPY Deployment ...................................................................................................... 411 Lab B............................................................................................................................... 412

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC xii All Rights Reserved

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 1 All Rights Reserved

    Chapter 1

    Introduction to ASP.NET MVC

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 2 All Rights Reserved

    Introduction to ASP.NET MVC

    Objectives

    After completing this unit you will be able to:

    Describe advantages and disadvantages of ASP.NET Web Forms.

    Understand the Model-View-Controller (MVC) pattern

    Outline the parts of an ASP.NET MVC application.

    Describe advantages and disadvantages of ASP.NET MVC.

    Understand the use of unit testing in creating ASP.NET MVC applications.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 3 All Rights Reserved

    Review of ASP.NET Web Forms

    ASP.NET Web Forms provide a way to build web applications.

    You can use compiled, object-oriented languages with ASP.NET, including C# and Visual Basic.

    All the power of the .NET Framework is available to you, including the extensive class library.

    Code and presentation elements can be cleanly separated.

    Code can be provided in a separate section of a Web page from user interface elements.

    The separation can be carried a step further by use of separate “code behind” files.

    ASP.NET Web Forms comes with an extensive set of server controls that provide significant functionality out of the box.

    Server controls transparently handle browser compatibility issues.

    A special set of Mobile Controls can emit either HTML or WML, depending on the characteristics of the client device.

    Configuration is handled by XML files without need of any registry settings, and deployment can be done simply by copying files.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 4 All Rights Reserved

    Advantages of ASP.NET Web Forms

    ASP.NET Web Forms continue to be supported and have their own advantages:

    A rich event model supported in hundreds of server controls facilitates easy development of Web server applications, following a familiar GUI development paradigm.

    View state makes it easy to manage state information.

    The model works well for individuals and small teams doing rapid application development.

    The large number of built-in and third-party components also facilitates rapid application development.

    In general, Web Forms are quite easy to work with and generally require less code.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 5 All Rights Reserved

    Disadvantages of ASP.NET Web Forms

    Key disadvantages of ASP.NET Web Forms include

    ViewState tends to be large depending on the number of server controls contained on the page, thus increasing the size of the page and the length of the response time from server to browser

    ASP.NET Web Forms provide tight coupling with the code-behind classes which make automated testing of the back-end code apart from the web pages more difficult

    Because the code-behind classes are so tightly coupled to the web forms, developers are encouraged to mix presentation code with application logic in the same code-behind classes which can lead to fragile and unintelligible code

    Limited control of HTML rendered through use of server controls

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 6 All Rights Reserved

    Model-View-Controller Pattern

    The Model-View-Controller (MVC) design pattern divides an application into three conceptual components:

    A model represents the data and operations that are meaningful to the domain of the application. It implements the application logic for the domain.

    Views display a user interface for portions of the model. Typically the UI is created from model data.

    Controllers handle incoming requests, work with the model, and select a view to render a UI back to the user.

    Controller

    Model

    View

    User

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 7 All Rights Reserved

    ASP.NET MVC

    ASP.NET MVC is a framework based on ASP.NET for creating Web applications.

    It is an alternative to Web Forms.

    ASP.NET MVC 1.0 was installed on top of .NET 3.5 SP1 and Visual Studio 2008 SP.

    ASP.NET MVC 2.0 is integrated into .NET 4.0 and Visual Studio 2010.

    ASP.NET MVC 3.0 is a separate download and adds important new features, such as the Razor view engine.

    ASP.NET MVC 4.0 is integrated into .NET 4.5 and Visual Studio 2012.

    ASP.NET MVC 5.0 is integrated into .NET 4.5.x/4.6 and Visual Studio 2013/2015.

    ASP.NET MVC 6.0, part of ASP.NET vNext, will unify MVC with Web API.

    Expected release is in Q1 2016.

    ASP.NET MVC does not replace Web Forms but is an alternative approach to creating Web applications.

    It relies on the same ASP.NET infrastructure as does Web Forms and is integrated with ASP.NET features such as master pages and membership-based authentication.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 8 All Rights Reserved

    Advantages of ASP.NET MVC

    Key advantages of ASP.NET MVC include:

    The MVC pattern promotes separation of concerns into input logic (controller), business logic (model) and UI (view). This aids in managing complexity.

    These components are loosely coupled, promoting parallel development.

    This loose coupling also facilitates automated testing.

    Views are created using standard HTML and cascading style sheets, giving the developer a high degree of control over the user interface.

    There is no view state, reducing the load on the browser in rendering a page.

    Separation of Concerns:

    Each component has one responsibility

    SRP – Single Responsibility Principle

    DRY – Don’t Repeat Yourself

    More easily testable

    Helps with concurrent development

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 9 All Rights Reserved

    Disadvantages of ASP.NET MVC

    Key disadvantages of ASP.NET MVC include:

    Writing View contents the old ASP-like way (though this is now easier with the newer Razor view syntax).

    Unit testing and Test Driven Development (TDD) are encouraged and used more but also bring a steep learning curve.

    Need to understand HTML controls and style sheets, but at the same time this allows a designer to work independently of the coders.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 10 All Rights Reserved

    Goals of ASP.NET MVC

    The ASP.NET MVC Framework has the following goals:

    Frictionless Testability

    Tight control over markup

    User/Search Engine friendly URLs

    Leverage the benefits of ASP.NET

    Conventions and Guidance

    Extensibility

    Replace any component of the system

    Interface-based architecture

    Very few sealed methods / classes

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 11 All Rights Reserved

    Unit Testing

    Unit testing lets you specify the expected behavior of individual classes or other small code units in isolation.

    ASP.NET MVC encourages unit testing of the Models and the Controllers of the application to verify expected behaviors.

    Separation of concerns makes unit testing of individual components feasible.

    You may use Microsoft’s Visual Studio Unit Test Framework for unit testing or other unit test framework such as NUnit.

    NUnit is free open source software.

    Visual Studio Unit Test Framework is now built into the free Community version of Visual Studio 2015 and is used in this course.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 1

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 12 All Rights Reserved

    Summary

    ASP.NET Web Forms is still used and has both advantages and disadvantages compared to MVC.

    The Model-View-Controller (MVC) pattern is useful in creating applications that have separation of concerns.

    Unit testing is helpful and encouraged in developing ASP.NET MVC applications

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 335 All Rights Reserved

    Chapter 11

    ASP.NET Web API

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 336 All Rights Reserved

    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

    Implement Web API clients.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 337 All Rights Reserved

    ASP.NET Web API

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

    It is built in to 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 2015 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 338 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 339 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).

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 340 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 341 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 342 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 { } }

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 343 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 344 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 could also have clicked Open, and the file will be displayed in the Visual Studio editor.)

    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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 345 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 346 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; }

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 347 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 for .NET4):

    http://www.telerik.com/download/fiddler Bring up Fiddler4 and start recording HTTP traffic.

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

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 348 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 they are in Raw format.

    GET http://localhost:55120/api/demo HTTP/1.1 Accept: text/html, application/xhtml+xml, */* Accept-Language: en-US User-Agent: Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko Accept-Encoding: gzip, deflate Connection: Keep-Alive Host: localhost:55120 HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 ... X-Powered-By: ASP.NET Date: Tue, 03 Nov 2015 15:06:28 GMT Content-Length: 15 "Hello Web API"

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 349 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: text/html, application/xhtml+xml, */* Accept-Language: en-US Content-Type: application/json User-Agent: Mozilla/5.0 (Windows NT 6.1; ... Accept-Encoding: gzip, deflate Connection: Keep-Alive Host: localhost:55120

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

    "Goodbye"

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 350 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 and click Execute. Here is the response in WebView.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 351 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 MVC 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 352 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). Comment out the [Authorize] attribute.

    public class ValuesController : ApiController { // GET api/values public IEnumerable 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) { } }

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 353 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 Visual Studio.

    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(); GlobalConfiguration.Configure( WebApiConfig.Register); FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters); RouteConfig.RegisterRoutes( RouteTable.Routes); BundleConfig.RegisterBundles( BundleTable.Bundles); }

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 354 All Rights Reserved

    Route Registration

    Examine WebApiConfig.cs in the App_Start folder. public static void Register(HttpConfiguration config) { ... // Web API routes config.MapHttpAttributeRoutes(); 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 355 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.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 356 All Rights Reserved

    String API Demo (Cont’d)

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

    public class StringsController : ApiController { private static List info = new List(); 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 Get() { return info; } 11. Specify api/strings as the Start Action.

    12. Build and run. Examine the output in Visual Studio.

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

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 357 All Rights Reserved

    Lab 11A

    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 11A write-up at the end of the chapter.

    Suggested time: 30 minutes

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 358 All Rights Reserved

    HTTP Response Codes

    The example from the demo and lab returns default HTTP codes for various conditions.

    HTTP 204 No Content for a successful POST.

    HTTP 500 Internal Server Error for giving an index out of range in GET and PUT.

    It would be preferable to give response codes that are consistent with HTTP standards and to give better error return codes and messages.

    We can customize response codes and messages by using HttpResponseMessage as the return type in our controller action methods.

    Here is improved code to retrieve a specific string from the list.

    // GET api/strings/5 public HttpResponseMessage Get(int id) { if (id < info.Count) { return Request.CreateResponse( HttpStatusCode.OK, info[id]); } else return Request.CreateErrorResponse( HttpStatusCode.NotFound, "string not found"); }

    This returns HTTP 404 Not Found for index out of range.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 359 All Rights Reserved

    POST Response Code

    The HTTP standard suggests a return code of 201 Created for success.

    You should also set a Location in the response header to the URI of the newly created item.

    Here is improved code for POST. // POST api/strings public HttpResponseMessage Post( [FromBody]string value) { info.Add(value); var msg = Request.CreateResponse( HttpStatusCode.Created); msg.Headers.Location = new Uri( Request.RequestUri + (info.Count - 1).ToString()); return msg; }

    This returns HTTP 201 Created.

    The URI of the newly created item is in the Location field of the header.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 360 All Rights Reserved

    HttpResponseException

    Another way to propagate a suitable error response code is to throw an HttpResponseException.

    Here is improved code for DELETE. // DELETE api/strings/5 public void Delete(int id) { if (id >= info.Count) { throw new HttpResponseException( HttpStatusCode.NotFound); } info.RemoveAt(id); } The complete improved example is in

    MvcStringApi\Step3 in the chapter folder.

    You can exercise it in Fiddler, experimenting with the various return codes and messages.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 361 All Rights Reserved

    Web API Clients

    You can create a .NET client of a Web API service by using the class HttpClient.

    This and related classes are contained in the Microsoft ASP.NET Web API 2 Client Libraries package, which is available via NuGet.

    Search for “webapi client”.

    After it is installed in your project, you will have references to these assemblies:

    Microsoft.Json

    System.Net.Http

    System.Net.Http.Formatting

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 362 All Rights Reserved

    HttpClient

    The key class in the Web API 2 Client Libraries is HttpClient.

    This class provides functionality to send HTTP requests and receive HTTP responses from a resource identified by a URI.

    An instance of HttpClient acts as a session to send HTTP requests.

    It maintains a collection of settings that are applied to all requests executed by that session.

    Settings for features such as authentication and caching can be configured in a WebRequestHandler object.

    This object can be passed to an HttpClient instance via a constructor.

    HttpWebRequest is used by default to send requests to the server, but this behavior can be modified.

    HttpClient can also be used as a base class for more specialized HTTP clients.

    For example, a hypothetical FacebookHttpClient could provide additional methods, such as GetFriends().

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 363 All Rights Reserved

    Initializing HttpClient

    To use an instance of HttpClient you should at least specify the following:

    The base address

    The formats that can be used in Accept headers (JSON, XML, etc.)

    Here is typical code: HttpClient client = new HttpClient(); client.BaseAddress = new Uri( "http://localhost:49569/"); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue( "application/json"));

    The port number in the base address should be the same as that used by the server.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 364 All Rights Reserved

    Issuing a GET Request

    There are four basic steps in issuing a GET request.

    1. Use one of the overloaded GetAsync() methods of HttpClient to issue a GET request to a specified URI. Obtain the result, such as by using the (blocking) Result property. This will return an HttpResponseMethod object.

    2. Test for success via the property IsSuccessStatusCode. If failure, use the properties StatusCode and ReasonPhrase to display an error message.

    3. Parse the body of the response using the ReadAsAsync() method of the Content property.

    4. Obtain the result, such as by use of the (blocking) Result property.

    HttpResponseMessage response = client.GetAsync( "api/strings").Result; // Blocking call! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! var strings = response.Content.ReadAsAsync ().Result; foreach (var str in strings) { Console.WriteLine(str); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); }

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 365 All Rights Reserved

    Issuing a POST Request

    You can do a POST via the PostAsJsonAsync() method of HttpClient.

    The relevant return information is the URI of the new resource, which is passed in the response header.

    Sample code: Uri stringUri = null; HttpResponseMessage response = client.PostAsJsonAsync( "api/strings/", str).Result; if (response.IsSuccessStatusCode) { stringUri = response.Headers.Location; return stringUri; } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); return null; } Other HTTP requests are made similarly.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 366 All Rights Reserved

    Lab 11B

    A .NET Client of String API Service

    In this lab you will use the Web API 2 Client Libraries package to implement a Console client program of the String API service. You are provided with starter code that implements a user interface for interactively testing the service.

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

    Suggested time: 45 minutes

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 367 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

    Microsoft ASP.NET Web API 2 Client Libraries is a NuGet package that facilitates creating .NET clients of Web API services.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 368 All Rights Reserved

    Lab 11A

    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\AspCs Directories: Labs\Lab11A\MvcStringApi (do your work here) Chap11\MvcStringApi\Step1 (starter code) Chap11\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 (Index.cshtml) 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:

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 369 All Rights Reserved

    api/strings/1 4. Examine the output in Visual Studio.

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

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 370 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; } 12. Build and run. Use Fiddler to exercise PUT with an index of 1 and a new string

    “beetle”.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 371 All Rights Reserved

    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” and “gamma”. You’re done!

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 372 All Rights Reserved

    Lab 11B

    A .NET Client of String API Service

    Introduction In this lab you will use the Web API 2 Client Libraries package to implement a Console client program of the String API service. You are provided with starter code that implements a user interface for interactively testing the service. Suggested Time: 45 minutes Root Directory: C:\OIC\AspCs Directories: Labs\Lab11B\StringApiClient (do your work here) Chap11\StringApiClient\Step0 (starter code) Chap11\StringApiClient\Step1 (solution) Chap11\MvcStringApi\Step3 (string API service) Instructions 1. Build and run the starter code. Type “help” to see a list of the legal commands. Type

    “quit” to exit the program. Examine the starter code. There is a simple loop for exercising various commands. A simple InputWrapper class is provided for doing console input.

    2. In Solution Explorer, right-click over the project and choose Manage NuGet Packages from the context menu. Do a search for “webapi client” to find the Microsoft.AspNet.WebApi.Client package. Install this package. The References in the project now include Newtonsoft.Json, System.Net.Http, and System.Net.Http.Formatting.

    3. Add code to the Program class to initialize a static data member client of type HttpClient. You will also need to import the System.Net.Http namespace.

    ... using System.Net.Http; namespace StringApiClient { class Program { static HttpClient client = new HttpClient(); static void Main(string[] args) { InputWrapper iw = new InputWrapper(); InitHttpClient(); ...

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 373 All Rights Reserved

    4. Provide the following code to implement InitHttpClient(). You will need to import the namespace System.Net.Http.Headers. Be careful to provide the port number that is used by your version of MvcStringApi.

    private static void InitHttpClient() { client.BaseAddress = new Uri("http://localhost: 55465/"); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); } 5. Provide the following code for Show(), which will implement a GET request.

    private static void Show() { HttpResponseMessage response = client.GetAsync("api/strings").Result; // Blocking call! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! var strings = response.Content.ReadAsAsync().Result; foreach (var str in strings) { Console.WriteLine(str); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } } 6. Run Step 3 of the MvcStringApi program. This should bring up the browser

    displaying a little help page for the URIs that can be exercised in the browser. Leave it running.

    7. Build and run StringApiClient. You should see the list of strings displayed.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 374 All Rights Reserved

    8. Next we will implement ShowOne(), which displays a single string at a given index position. Begin by copying the code for Show(). There are two pieces of code we need to change.

    a. We need to change the relative URI passed to client.GetAsync().

    "/api/strings/" + id.ToString()

    b. We need to change the code to parse the response body. Now we obtain a single string, not IEnumerable. And the result we display is a single string, so we don’t need a loop.

    // Parse the response body. Blocking! var str = response.Content.ReadAsAsync().Result; Console.WriteLine(str); 9. Build and run. Test with indices 0, 2 and one out of range, such as 3. You should get

    output like this:

    > showone index: 0 alpha > showone index: 2 gamma > showone index: 3 404 (Not Found) > 10. Type “quit” to exit.

    11. Next, implement Add(), which will send a POST request and return the URI of the resource that was added to the list.

    private static Uri Add(string str) { Uri stringUri = null; HttpResponseMessage response = client.PostAsJsonAsync("api/strings/", str).Result; if (response.IsSuccessStatusCode) { stringUri = response.Headers.Location; return stringUri; } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); return null; } }

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 375 All Rights Reserved

    12. We also have to modify the user interface code to display the URI of the resource that is returned.

    else if (cmd == "add") { string str = iw.getString("string: "); Uri stringUri = Add(str); Console.WriteLine("stringUri = {0}", stringUri); } 13. Build and test. Add a single string and show the results afterwards. You should get

    output like this:

    > add string: delta stringUri = http://localhost:49569/api/strings/3 > show alpha beta gamma delta > 14. Next, implement Update(), which will send a PUT request.

    private static void Update(Uri stringUri, string str) { HttpResponseMessage response = client.PutAsJsonAsync(stringUri.PathAndQuery, str).Result; Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } 15. Add code that will build the appropriate request URI from the data the use inputs and

    then call Update().

    else if (cmd == "update") { int id = iw.getInt("index: "); string str = iw.getString("string: "); Uri stringUri; if (Uri.TryCreate(client.BaseAddress, "/api/strings/" + id.ToString(), out stringUri)) { Console.WriteLine("stringUri = {0}", stringUri); Update(stringUri, str); } else Console.WriteLine("Could not create Uri"); } 16. Build and test.

    17. Finally, implement Delete(), which will send a DELETE request.

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    MvcCs Chapter 11

    Rev. 4.7 Copyright © 2015 Object Innovations Enterprises, LLC 376 All Rights Reserved

    private static void Delete(Uri stringUri) { HttpResponseMessage response = client.DeleteAsync(stringUri).Result; Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } 18. Provide the appropriate user interface code to test calling Delete(). Again we need to

    build the appropriate request URI from the data the use inputs.

    else if (cmd == "delete") { int id = iw.getInt("index: "); Uri stringUri; if (Uri.TryCreate(client.BaseAddress, "/api/strings/" + id.ToString(), out stringUri)) { Console.WriteLine("stringUri = {0}", stringUri); Delete(stringUri); } else Console.WriteLine("Could not create Uri"); } 19. Build and test. You are done!

    Unauthorized Reproduction or Distribution Prohibited

  • EVALUATION COPY

    7400 E. Orchard Road, Suite 1450 NGreenwood Village, Colorado 80111

    Ph: 303-302-5280www.ITCourseware.com

    1-00-00363-000-03-08-16

    Unauthorized Reproduction or Distribution Prohibited