ASP.NET CORE MVC STUDENT WORKBOOK · Chapter 1 Introduction to ASP.NET Core MVC Chapter 2 Getting...

of 58 /58
ASP.NET CORE MVC STUDENT WORKBOOK Evaluation Copy Unauthorized Reproduction or Distribution Prohibited

Embed Size (px)

Transcript of ASP.NET CORE MVC STUDENT WORKBOOK · Chapter 1 Introduction to ASP.NET Core MVC Chapter 2 Getting...

  • ASP.NET CORE MVCSTUDENT WORKBOOK

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC ii All Rights Reserved

    ASP.NET Core MVC Rev. 1.0 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 ©2017 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC iii All Rights Reserved

    Table of Contents (Overview) Chapter 1 Introduction to ASP.NET Core MVC Chapter 2 Getting Started with ASP.NET Core MVC Chapter 3 ASP.NET MVC Architecture Chapter 4 The Model Chapter 5 The Controller Chapter 6 The View Chapter 7 Routing Chapter 8 ASP.NET Core Web API Appendix A Learning Resources

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC iv All Rights Reserved

    Directory Structure

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

    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.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC v All Rights Reserved

    Table of Contents (Detailed)

    Chapter 1: Introduction to ASP.NET Core 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 ASP.NET Core.................................................................................................................... 8 What is .NET Core?............................................................................................................ 9 Advantages of ASP.NET MVC ........................................................................................ 10 Disadvantages of ASP.NET MVC.................................................................................... 11 Goals of ASP.NET MVC.................................................................................................. 12 Unit Testing ...................................................................................................................... 13 Summary ........................................................................................................................... 14

    Chapter 2: Getting Started with ASP.NET Core MVC .................................................. 15 An ASP.NET Core MVC Testbed .................................................................................... 17 Visual Studio ASP.NET MVC Demo............................................................................... 18 Restoring Packages ........................................................................................................... 20 Starter Application............................................................................................................ 21 Simple App with Controller Only..................................................................................... 23 Edit project.json File......................................................................................................... 24 Edit Startup.cs ................................................................................................................... 25 Action Methods and Routing............................................................................................ 31 Action Method Return Type ............................................................................................. 32 Rendering a View ............................................................................................................. 33 Creating a View ................................................................................................................ 34 The View Web Page ......................................................................................................... 35 Dynamic Output................................................................................................................ 36 Razor View Engine ........................................................................................................... 37 Embedded Scripts ............................................................................................................. 38 Embedded Script Example................................................................................................ 39 Using a Model with ViewBag .......................................................................................... 40 Controller Using Model and ViewBag ............................................................................. 41 View Using Model and ViewBag..................................................................................... 42 Using Model Directly ....................................................................................................... 43 Passing Parameters in Query String.................................................................................. 44 Lab 2 ................................................................................................................................. 45 Summary ........................................................................................................................... 46

    Chapter 3: ASP.NET MVC Architecture......................................................................... 53 The Controller in ASP.NET MVC.................................................................................... 55 The View in ASP.NET MVC ........................................................................................... 56 The Model in ASP.NET MVC.......................................................................................... 57

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC vi All Rights Reserved

    How MVC Works ............................................................................................................. 58 Using Forms...................................................................................................................... 59 HTML Helper Functions .................................................................................................. 60 Handling Form Submission .............................................................................................. 61 Model Binding .................................................................................................................. 62 Greet View........................................................................................................................ 63 Input Validation ................................................................................................................ 64 Nullable Type ................................................................................................................... 65 Checking Model Validity.................................................................................................. 66 Validation Summary ......................................................................................................... 67 Lab 3 ................................................................................................................................. 68 Summary ........................................................................................................................... 69

    Chapter 4: The Model ........................................................................................................ 77 Complex Models............................................................................................................... 79 MvcBooks Example.......................................................................................................... 80 The View........................................................................................................................... 81 The Model: Book and Category........................................................................................ 82 The Model: DB ................................................................................................................. 83 MvcBooks – Step 2........................................................................................................... 84 Books by Category............................................................................................................ 85 Books by Category – View............................................................................................... 86 Running Step 2.................................................................................................................. 87 Microsoft Technologies for the Model ............................................................................. 88 NuGet Package Manager .................................................................................................. 89 Installed Packages............................................................................................................. 90 Installing a Package .......................................................................................................... 91 Updated project.json ......................................................................................................... 92 XML Serialization Demo.................................................................................................. 93 Running the Starter Code.................................................................................................. 95 XML Serialization: Save .................................................................................................. 96 System.Xml.XmlSerializer Package................................................................................. 98 Deserialization ................................................................................................................ 101 XML Serialization .......................................................................................................... 102 What Will Not Be Serialized .......................................................................................... 103 Lab 4 ............................................................................................................................... 104 XML as a Data Store ...................................................................................................... 105 MvcBooks – Model ........................................................................................................ 106 Save() .............................................................................................................................. 107 Restore().......................................................................................................................... 108 AddCategory() ................................................................................................................ 109 MvcBooks – Controller .................................................................................................. 110 Adding a Category .......................................................................................................... 111 View for Adding a Category........................................................................................... 112 Running the Example...................................................................................................... 113 SmallPub Database ......................................................................................................... 114

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC vii All Rights Reserved

    Using ADO.NET............................................................................................................. 116 Model .............................................................................................................................. 117 Controller and View........................................................................................................ 118 Running the Database Example ...................................................................................... 119 Summary ......................................................................................................................... 120

    Chapter 5: The Controller ............................................................................................... 127 Controller Base Class...................................................................................................... 129 Controller Base Class...................................................................................................... 130 Action Methods............................................................................................................... 131 Action Method Example ................................................................................................. 132 Index() Action Method ................................................................................................... 133 Info() Action Method...................................................................................................... 134 Info.cshtml ...................................................................................................................... 135 Running the Example...................................................................................................... 136 Receiving Input............................................................................................................... 137 Binding Example ............................................................................................................ 138 Non-Nullable Parameters................................................................................................ 139 Nullable Parameters ........................................................................................................ 140 Using a Model................................................................................................................. 141 Action Results................................................................................................................. 142 Action Result Example ................................................................................................... 143 Output Demo................................................................................................................... 144 JavaScript Object Notation ............................................................................................. 147 Serving Static Files ......................................................................................................... 148 Action Method Attributes ............................................................................................... 149 Lab 5 ............................................................................................................................... 150 Filters .............................................................................................................................. 151 Asynchronous Controllers .............................................................................................. 153 Summary ......................................................................................................................... 154

    Chapter 6: The View......................................................................................................... 161 View Responsibility........................................................................................................ 163 A Program with a View .................................................................................................. 164 View Page ....................................................................................................................... 165 Passing Data to the View ................................................................................................ 166 Dynamic and ExpandoObject ......................................................................................... 167 Passing Lists to the View................................................................................................ 168 HTML Helper Methods .................................................................................................. 169 Link-Building Helpers .................................................................................................... 170 Form Helpers .................................................................................................................. 171 Html Helper Example ..................................................................................................... 172 Validation Helpers .......................................................................................................... 174 Templated Helpers .......................................................................................................... 175 Validation in Model ........................................................................................................ 177 Validation in Controller .................................................................................................. 178

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC viii All Rights Reserved

    ValidationMessage Helper.............................................................................................. 179 Running the Example...................................................................................................... 180 Lab 6 ............................................................................................................................... 181 Summary ......................................................................................................................... 182

    Chapter 7: Routing ........................................................................................................... 189 ASP.NET Routing........................................................................................................... 191 Routing in ASP.NET Core MVC.................................................................................... 192 Simple Route Example ................................................................................................... 193 Math Controller............................................................................................................... 194 Default Values for URL Parameters ............................................................................... 196 Using a Default Route..................................................................................................... 197 Home Controller ............................................................................................................. 198 Assigning Parameter Values ........................................................................................... 199 Controller Code............................................................................................................... 200 View Code ...................................................................................................................... 201 Running the Example...................................................................................................... 202 Properties of Routes........................................................................................................ 203 Optional Parameter ......................................................................................................... 204 Optional Parameter Demo............................................................................................... 205 Matching URLs to Route ................................................................................................ 210 Defaults ........................................................................................................................... 211 Multiple Routes Example ............................................................................................... 212 Attribute Routing ............................................................................................................ 216 Combining Routes .......................................................................................................... 217 Empty String for Route Attribute ................................................................................... 218 Token Replacement ........................................................................................................ 219 Summary ......................................................................................................................... 220

    Chapter 8: ASP.NET Core Web API.............................................................................. 221 ASP.NET Core Web API................................................................................................ 223 REST............................................................................................................................... 224 Representation, State and Transfer ................................................................................. 225 Collections and Elements................................................................................................ 226 Web API Demo............................................................................................................... 227 Strings Controller............................................................................................................ 230 Project Settings ............................................................................................................... 233 HTTP Testing Tools ....................................................................................................... 234 Using Postman ................................................................................................................ 235 Implementing and Testing POST.................................................................................... 237 Lab 8A ............................................................................................................................ 240 HTTP Response Codes ................................................................................................... 241 Testing Improved Code for GET .................................................................................... 242 POST Response Code ..................................................................................................... 243 Named Route .................................................................................................................. 244 Testing Improved Code for POST .................................................................................. 245

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC ix All Rights Reserved

    Location Header.............................................................................................................. 246 Response Code for PUT and DELETE........................................................................... 247 Web API Clients ............................................................................................................. 248 HttpClient........................................................................................................................ 249 Initializing HttpClient ..................................................................................................... 250 Issuing a GET Request ................................................................................................... 251 Issuing a POST Request ................................................................................................. 252 Lab 8B............................................................................................................................. 253 Summary ......................................................................................................................... 254

    Appendix A Learning Resources .............................................................................. 263 Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC x All Rights Reserved

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 1 All Rights Reserved

    Chapter 1

    Introduction to ASP.NET Core MVC

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 2 All Rights Reserved

    Introduction to ASP.NET Core 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.

    Describe ASP.NET Core.

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

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 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.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 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.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 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

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 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

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 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 in classical .NET.

    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 Core unifies MVC with Web API.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 8 All Rights Reserved

    ASP.NET Core

    ASP.NET Core is a completely new version of ASP.NET that is open-source and cross-platform.

    It runs on Windows, Mac and Linux.

    It runs on either .NET Core or the full .NET Framework.

    ASP.NET Core is very modular providing flexibility in using what is needed for an application with minimal overhead.

    ASP.NET Core supports both MVC and Web API in an integrated manner but it does not support Web Forms.

    This course focuses on MVC running on .NET Core, with an introduction to Web API in the final chapter.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 9 All Rights Reserved

    What is .NET Core?

    .NET Core is a general purpose development platform that is cross-platform, supporting:

    Windows

    macOS

    Linux

    It is open-source (MIT license) maintained by Microsoft and the .NET community on GitHub.

    .NET Core is composed of:

    A .NET runtime

    A set of framework libraries

    A set of SDK tools and language compilers

    The app host dotnet, which is used to launch .NET Core apps.

    .NET Core is distributed through NuGet packages.

    Packages are relatively fine grained, allowing smaller app size.

    Metapackages are more coarse-grained, describing a set of packages that are meaningful together.

    NuGet is the package manager for the Microsoft development platform. It provides a gallery as a central repository.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 10 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

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 11 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.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 12 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

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 13 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.

    There are several choices for unit testing in .NET Core.

    The new dotnet test supports cross-platform testing.

    Microsoft’s MSTest is integrated into Visual Studio and can be used for testing .NET Core on Windows.

    The open-source xUnit can be used for testing .NET Core applications.

    This link provides information on unit testing in .NET Core:

    https://docs.microsoft.com/en-us/dotnet/articles/core/testing/

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 1

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 14 All Rights Reserved

    Summary

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

    But Web Forms is not available in ASP.NET Core.

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

    ASP.NET Core is open-source and cross platform and unifies MVC and Web API.

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

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 127 All Rights Reserved

    Chapter 5

    The Controller

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 128 All Rights Reserved

    The Controller

    Objectives

    After completing this unit you will be able to:

    Describe the facilities provided by the Controller base class:

    Action methods

    Action results

    Filters

    Describe the ways controllers can receive input.

    Describe the principal types of output from a controller.

    Use attributes to control how actions are invoked.

    Describe how asynchronous controllers work and how they can be used.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 129 All Rights Reserved

    Controller Base Class

    In a nutshell, controllers are responsible for application logic.

    The Controller class is responsible for the following processing stages:

    Locating the appropriate action method to call and validating that it can be called.

    Getting the values to use as the action method's arguments.

    Handling all errors that might occur during the execution of the action method.

    Providing the default RazorViewEngine class for rendering views, populating it in the ViewEngineCollection property.

    ASP.NET Core does not give you access to the IController interface.

    You always implement a controller by deriving from the Controller base class.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 130 All Rights Reserved

    Controller Base Class

    The Controller base class introduces the following facilities:

    Action Methods

    Action Results

    Filters

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 131 All Rights Reserved

    Action Methods

    Every public method in a controller is an action method.

    This means the method can be invoked by some URL

    When a user enters a URL into the browser, the MVC application uses routing rules defined in the Startup.cs file.

    app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });

    The controller then determines the appropriate action method to handle the request

    For example, if the URL contains /Products/Detail/5, then the MVC application will attempt to match the Products with a Products controller, the Detail with an action method in Products, and 5 as a parameter to the Detail action method

    public class ProductsController : Controller { public IActionResult Detail(int id) { ... Product product = prodRepository.Get(id); return View(product); } }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 132 All Rights Reserved

    Action Method Example

    The CtlHello example illustrates some of the functionality of the Controller base class.

    There is one controller.

    HomeController implements actions to display a help screen and to display selected information about the request.

    Note various features from use of the base class.

    There is an automatic dispatch to the proper action method based on the URL.

    Properties give convenient access to context data of the request.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 133 All Rights Reserved

    Index() Action Method

    public class HomeController : Controller { // GET: /Home public IActionResult Index() { return View(); } ... The corresponding view Index.cshtml provides the

    HTML for a simple help screen. Index Supported Action /Home /Home/Info Build and run.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 134 All Rights Reserved

    Info() Action Method

    The Info() action method displays context information about the HTTP request, using the Request property.

    // GET: /Home/Info public IActionResult Info() { List info = new List(); string queryString = Request.QueryString.ToString(); info.Add("query string = " + queryString); info.Add("HttpContext:"); var dict = Request.HttpContext.Items; foreach(KeyValuePair kvp in dict) { string item = string.Format( "Key = {0}, Value = {1}", kvp.Key, kvp.Value); info.Add(item); } var req = Request.Method; info.Add("method = " + req); long? length = Request.ContentLength; if (length.HasValue) info.Add("content length = " + length); req = Request.Path.ToString(); info.Add("path = " + req); ViewBag.Info = info; return View(); }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 135 All Rights Reserved

    Info.cshtml

    The controller stores the retrieved information in a List object that is passed to the view by using the ViewBag.

    The view provides Razor code to display this information in a bulleted list.

    Info Info About Request Object @foreach (string item in ViewBag.Info) { @:@item }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 136 All Rights Reserved

    Running the Example

    Build and run. Provide the following URL. Note the query string, which we will be using in our next example of a simple Math controller.

    http://localhost:59665/Home/Info?x=5&y=7

    This is the output:

    We will sometimes use the Chrome browser in our

    screenshots, because it conveniently displays the whole URL in the address field.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 137 All Rights Reserved

    Receiving Input

    A straightforward way that action methods can receive input is through context objects.

    The Controller base class has properties for various context objects, including Request, Response, RouteData, HttpContext, and Server.

    The previous example illustrates this approach. For example, parameters could be retrieved by parsing the query string. However, this is not very convenient, as you would need to provide the parsing code.

    Parameters can be passed to your action methods.

    The default route {controller}/{action}/{id} provides for a single id parameter as part of the URL.

    public IActionResult Detail(int id)

    Model binding can automatically associate named values from the context with parameters having the same name. This binding can also do type conversions for you.

    public string Add(int x, int y)

    If the model binder can’t find a match for a parameter, it will pass null for reference types. For a value type, you will get a zero. You can distinguish between the absence of a parameter and zero as a real value if you make the type nullable, such as int?.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 138 All Rights Reserved

    Binding Example

    CtlBinding illustrates parameter passing via the parameter binding feature of ASP.NET MVC.

    In Step 1 the parameters “x” and “y” are mandatory, and zero will be returned if they are not present.

    Here is the code for Step 1. We don’t have to extract data from context objects; it is supplied through parameters to the action methods. Simple!

    public class MathController : Controller { // GET: /Math/Add public string Add(int x, int y) { int sum = x + y; return string.Format("{0} + {1} = {2}", x, y, sum); } // GET: /Math/Subtract public string Subtract(int x, int y) { int diff = x - y; return string.Format("{0} - {1} = {2}", x, y, diff); } }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 139 All Rights Reserved

    Non-Nullable Parameters

    The parameters “x” and “y” in Step 1 are not nullable.

    This means if we leave one out, say by misspelling it, a zero will be returned.

    This is different behavior in ASP.NET Core from classical ASP.NET, where an exception will be thrown.

    URL (port number varies): http://localhost:61005/Math/Add?x=7&yy=5

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 140 All Rights Reserved

    Nullable Parameters

    The parameters “x” and “y” in Step 2 are nullable.

    The parameters are declared to be of type int?.

    We test for the presence of a value with the HasValue property, and when we use the variable as an integer we must perform an explicit cast.

    // GET: /Math/Add public string Add(int? x, int? y) { if (x.HasValue & y.HasValue) { int sum = (int)x + (int)y; return string.Format("{0} + {1} = {2}", x, y, sum); } else return "Please supply values for parameters x and y"; } Now if we leave one out, we’ll get an error message

    rather than a zero.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 141 All Rights Reserved

    Using a Model

    If there is a Model in our application, we can extend the binding process a step further.

    Create a class whose properties associate with named values from the context having the same name.

    See CtlModel in the chapter folder.

    namespace CtlModel.Models { public class Pair { public int x { get; set; } public int y { get; set; } } } You can then automatically use objects of this class

    type in your action methods. // GET: /Math/Add public string Add(Pair p) { int sum = p.x + p.y; return string.Format("{0} + {1} = {2}", p.x, p.y, sum); }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 142 All Rights Reserved

    Action Results

    An action method normally returns a result of type IActionResult.

    An action method can return any type, such as string, int, and so on, but then the return value is wrapped in an ActionResult

    The most common action of an action method is to call the View() helper method, which returns a result of type ViewResult, which derives from ActionResult.

    This table shows some of the important action result types, which all derive from ActionResult.

    Action Result Helper Method Description

    ViewResult View() Renders a view as a Web page, typically HTML

    RedirectResult Redirect() Redirects to another action method using its URL

    JsonResult Json() Returns a serialized Json object

    FileResult File() Returns binary data to write to the response

    ContentResult Content() Returns a string

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 143 All Rights Reserved

    Action Result Example

    CtlOutput illustrates a number of different Action Results.

    A simple view file Index.cshtml provides a user interface.

    Controller Output Demo Download Objectives.txt
    Redirect
    Json representation of a Person object (Uses GET)
    (Uses POST)

    The hyperlinks will generate GET requests, and the submit button will generate a POST request.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 144 All Rights Reserved

    Output Demo

    1. Build and run the example.

    2. Click on the first link. You can download the text file (which can be displayed by a choice of programs, such as Notepad). Examine the code in the controller.

    // GET: /Home/Download public ActionResult Download() { return File( "/Objectives.txt", "application/text"); } 3. Click on the second link. You will be redirected to another

    HTML page. Examine the code in the controller.

    // GET: /Home/Redirect public ActionResult Redirect() { return Redirect("/RedirectTarget.html"); }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 145 All Rights Reserved

    Output Demo (Cont’d)

    4. Click on the third link. The result depends on the browser. In IE you will see a message box allowing you to download the JSON data in a file. In Chrome the JSON will be displayed directly.

    5. A more secure practice is to make such a request only through a POST. Examine the code in the controller. (We’ll discuss the attributes shortly.)

    // POST: /Home/Json [HttpPost] [ActionName("Json")] public ActionResult Json2() { return Json(new Person()); }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 146 All Rights Reserved

    Output Demo (Cont’d)

    6. Click the button. This will cause a POST. In IE you will see a message box allowing you to download the JSON data in a file.

    7. Click Open. You can now examine this file in Visual Studio.

    8. Look again at the source code in the controller.

    public ActionResult Json2() { return Json(new Person()); }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 147 All Rights Reserved

    JavaScript Object Notation

    9. JavaScript Object Notation or JSON is a very terse way of representing objects. Examine the Person class, which is defined in the file Person.cs in the Models folder.

    public class Person { public string Name { get; set; } public int Age { get; set; } public Person() { Name = "John"; Age = 33; } } 10. Examine again the file in Visual Studio. Observe how

    concisely this object instance has been represented.

    {"Name":"John","Age":33} 11. Finally, there is one additional action method Path(), which

    returns a string using the Content() helper.

    // GET: /Home/Path public string Path() { string strPath = Request.Path.ToString(); return strPath; } 12. This concludes the demo.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 148 All Rights Reserved

    Serving Static Files

    There are two more features in ASP.NET Core that are required to make this example work.

    First, in the Configure() method in Startup.cs you must call UseStaticFiles().

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); ...

    This requires package Microsoft.AspNetCore.StaticFiles.

    Second, the static files to be served must be put in the wwwroot folder of your project.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 149 All Rights Reserved

    Action Method Attributes

    You can control how actions are invoked by using various attributes.

    Attributes such as [HttpGet] and [HttpPost] specify which HTTP verbs an action method will respond to.

    [HttpGet] public ActionResult Json() { return Json(new Person()); } The [ActionName] attribute allows you to specify a

    name for your action method different from the name of the method. It is useful if we have two action operations taking the same signature.

    [HttpPost] [ActionName("Json")] public ActionResult Json2() { return Json(new Person()); } The [NoAction] attribute specifies that a public

    method will not be treated as an action method.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 150 All Rights Reserved

    Lab 5

    User Interface via a Controller

    In this lab you will implement an ASP.NET Core MVC application to welcome a new contact who supplies a first and last name. Your program should be implemented using a controller and a static web page but without a view.

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

    Suggested time: 40 minutes

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 151 All Rights Reserved

    Filters

    Filters are .NET attributes that add extra steps to the request processing pipeline, letting you inject extra logic: before and after action methods run,

    before and after action results are executed,

    in the event of an unhandled exception.

    Filters are a clean and powerful way to implement cross-cutting concerns.

    This means behavior gets reused all over the place, not naturally fitting at any one place in a traditional object-oriented hierarchy.

    Classic examples: logging, authorization, and caching.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 152 All Rights Reserved

    Filters (Cont’d)

    This table shows the four basic filter types.

    Filter Type Interface When Run

    Authorization Filter

    IAuthorizationFilter First, before running any other filters or the action method

    Action Filter IActionFilter Before and after the action method is run

    Result Filter IResultFilter Before and after the action result is executed

    Exception Filter

    IExceptionFilter Only if another filter, the action method, or the action result throws an unhandled exception

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 153 All Rights Reserved

    Asynchronous Controllers

    Getting heavy traffic to your web site can be a good thing for your business, but it can also be bad if it introduces performance problems.

    Your web site may be suffering from long-running I/O operations such as slow database queries or HTTP requests to external web services

    Asynchronous controllers are introduced as a way to improve performance and scalability.

    To take advantage of processing asynchronous requests, your controller can inherit from AsyncController rather than Controller.

    public class ProductController : AsyncController { // ...

    } Your action methods would split into two methods:

    One with a suffix of Async and another with a suffix of Completed. public void ProductsListAsync() { // Asynchronously call a Web Service } public ContentResult ProductsListCompleted( IEnumerable products) { }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 154 All Rights Reserved

    Summary

    Controllers are responsible for application logic.

    You can implement a controller by deriving from the Controller base class.

    Controllers use Action Methods, Action Results, and Filters to process requests.

    Input data to action methods can come from model binding.

    There are many kinds of output data available from an HTTP request.

    You can use attributes to control how actions are invoked.

    Asynchronous controllers provide a scalable solution for certain situations.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 155 All Rights Reserved

    Lab 5

    User Interface via a Controller

    Introduction In this lab you will implement an ASP.NET Core MVC application to welcome a new contact who supplies a first and last name. Your program should be implemented using a controller and a static web page but without a view.

    Suggested Time: 40 minutes Root Directory: C:\OIC\MvcCore Directories: Labs\Lab5 (do your work here) Labs\Lab5\Default.html (web page for form) Chap05\CtlForm\Step1 (answer to Part 1) Chap05\CtlForm\Step2 (answer to Part 2) Part 1. Display a Static Web Page 1. Create a new ASP.NET Core Empty Web Application CtlForm in the working

    directory.

    2. In the usual manner enable the application for MVC. Begin by editing project.json to bring in the Microsoft.AspNetCore.Mvc package.

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 156 All Rights Reserved

    { "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.1", "type": "platform" }, "Microsoft.AspNetCore.Diagnostics": "1.0.0", "Microsoft.AspNetCore.Mvc": "1.0.1", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.1", "Microsoft.Extensions.Logging.Console": "1.0.0" }, ... 3. Build the application to restore the package you just added.

    4. Edit Startup.cs to bring in the MVC service.

    public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } 5. Continue editing Startup.cs to define the standard default routing in Configure().

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); ...

    6. Add a HomeController to the project. Supply the following code for the Index() action method. Note that we also modified the comment.

    // GET: /Home public IActionResult Index() { return Redirect("/Default.html"); }

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 157 All Rights Reserved

    7. Copy the file to the wwwroot folder in the project. The Index() method is intended to redirect to the Default.html page.

    8. Set a breakpoint on the call to Redirect() and run under the debugger. You should hit the breakpoint.

    9. Step out of the method. You won’t come to Default.html but rather to the project’s default action of displaying a “Hello World” message.

    10. You need to enable access to static files. Edit the Configure() method in Startup.cs.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); ... 11. If you build the application now, you will get an error message. Use the NuGet

    Package Manager to install the package Microsoft.AspNetCore.StaticFiles.

    12. Build and run. Now the program should compile, and you will hit the page Default.html, which displays a form for entering first and last name.

    Part 2. Display the Greeting 1. Examine the file Default.html. There is a form with an action specified:

    2. Build and run. Click the button. You will come back to the same page. If you put a

    breakpoint at the Redirect() call, you will see that it is hit every time you click the button. Was the method called from a GET or a POST?

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 158 All Rights Reserved

    3. It was called from a POST, in response to submitting the form when you clicked the Greet button.

    4. Now start to think about how you can obtain data from the form when you do a POST. You can do this through model binding, with or without creating a model. The code is clearest if we do implement a model. Create a Models folder and add a class Contact to it.

    5. Provide code to implement properties FirstName and LastName.

    public class Contact { public string FirstName { get; set; } public string LastName { get; set; } } 6. In the controller, provide an override of Index() with a Contact object passed as a

    parameter. This action method is intended to respond to POST requests, so you should provide a suitable comment.

    // POST: /Home/Index public string Index(Contact con) { ... 7. For the symbol Contact to be recognized you need to import the namespace

    CtlForm.Models.

    8. Now supply code in your new action method to extract the first and last names from the Contact object and return a suitable greeting message.

    public string Index(Contact con) { string first = con.FirstName; string last = con.LastName; return "Welcome, " + first + " " + last; } 9. Build the application. You should get a clean compile, as the two Index() methods

    have different signatures.

    10. But you hit an exception when you run the application and click the Greet button.

    11. Provide a suitable attribute on the second Index() method to specify it will respond to a POST, thus removing the ambiguity.

    // POST: /Home/Index [HttpPost] public string Index(Contact con) { ...

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

  • MvcCore Chapter 5

    Rev. 1.0 Copyright © 2017 Object Innovations Enterprises, LLC 159 All Rights Reserved

    12. Build and run. You should now see the greeting displayed on a separate page. You are done!

    Evaluation Copy

    Unauthorized Reproduction or Distribution Prohibited

    Chapter 1 - Introduction to ASP.NET Core MVCChapter 2 - Getting Started with ASP.NET Core MVCChapter 3 - ASP.NET MVC ArchitectureChapter 4 - The ModelChapter 5 - The ControllerChapter 6 - The ViewChapter 7 - RoutingChapter 8 - ASP.NET Core Web APIAppendix A - Learning Resources