Core MVC
Core MVC
NET Core
MVC Web Applications
Welcome!
<Affiliation/Company>
5
About This Course
Course
Audience Prerequisites
COURSE
ADO.NET.
• Describe the Microsoft Web Technologies stack and select an appropriate technology to use to
• Design the architecture and implementation of a web application that will meet a set of functional
• Configure the pipeline of ASP.NET Core web applications by using middleware and leverage
• Add controllers to an MVC application to manage user interaction, update models, and select and
return views.
• Develop a web application that uses the ASP.NET Core routing engine to present friendly URLs and a
• Create views, which display and edit data and interact with models and controllers, in an MVC
application.
• Create MVC models and write code that implements business logic within model methods, properties,
and events.
• Implement a consistent look and feel across an entire MVC web application.
• Write JavaScript code that runs on the client-side and utilizes the jQuery script library to optimize the
• Run unit tests and debugging tools against a web application in Visual Studio 2017.
• Write an MVC application that authenticates and authorizes users to access content securely by using
Identity.
• Describe what a Web API is and why developers might add a Web API to an application.
• Describe how to package and deploy an ASP.NET Core MVC web application from a development
• Module 1: Exploring ASP.NET Core MVC • Module 7: Using Layouts, CSS, and JavaScript
• Module 6: Using Entity Framework Core in • Module 12: Implementing Web APIs
ASP.NET Core
• Module 13: Hosting and Deployment
13
Module 01
Exploring ASP.NET Core MVC
14
Module Overview
Overview of ASP.NET
01
Overview of Microsoft
Web Technologies 02 4.x
Introduction to
03 ASP.NET Core MVC
Lesson 1: Overview of Microsoft Web Technologies
01 02 03 04
Introduction to Overview of Client-Side Web Hosting
Microsoft Web ASP.NET Technologies Technologies
Technologies
Introduction to Microsoft Web Technologies
Server-Side Client-Side
• Programming Models:
ASP.NET
• ASP.NET 4.x:
• Web Pages
• Web Forms
• Web API
• ASP.NET Core:
• Razor Pages
Client-Side Web Technologies
<p>
• JavaScript
Content
• jQuery </p>
• AJAX p{
color: black;
• Angular }
• React
• And more
Hosting Technologies
• IIS
• Features
• Scaling
• Perimeter Networks
• IIS Express
• Web Apps
• Virtual Machines
• Mobile Apps
• Media Services
Lesson 2: Overview of ASP.NET 4.x
01 02 03
Overview of Web Overview of Web Overview of MVC
Pages Forms
04 05 06
Discussion: Shared ASP.NET Overview of Web
ASP.NET 4.x 4.x Features API
Application
Scenarios
Overview of Web Pages
<h2>Special Offers</h2>
<p>Get the best possible value on Northwind specialty
foods by taking advantage of these offers:</p>
@foreach (var item in offers) {
<div class="offer-card">
<div class="offer-picture">
@if (!String.IsNullOrEmpty(item.PhotoUrl)){
<img src="@Href(item.PhotoUrl) alt="@item.Title" />
}
</div>
</div>
}
Overview of Web Forms
01 02 03
Introduction to Discussion: Choose between
ASP.NET Core Choose between .NET Core and
ASP.NET 4.x and .NET Framework
ASP.NET Core
04 05
Models, Views, Demonstration:
and Controllers How to Explore
an ASP.NET Core
MVC Application
Introduction to ASP.NET Core
• Cloud-ready
• MVC
• Razor pages
• Web API
Razor Pages
@page
@model HomePageModel
<h1>@Model.Title</h1>
<h2>@Model.Description</li>
Discussion
Choose between ASP.NET 4.x and
ASP.NET Core
Choose between .NET Core and .NET Framework
You should use .NET Core when: You should use .NET Framework when:
• You want your code to run cross- • You want to extend an existing
platform application that uses .NET Framework
• You want to create microservices • You want to use NuGet packages or
• You want to use Docker containers third-party .NET libraries that are not
• You want to achieve a high-preforming supported in .NET Core
scalable system • You want to use .NET technologies that
aren't supported in .NET Core
• You want to use a platform that doesn’t
support .NET Core
Models, Views, and Controllers
SQL
View Model
Database
Controller
HTTP
Web Server
Browser
Demonstration: How to Explore an ASP.NET Core
MVC Application
40
Module Overview
Designing Models,
01
Planning in the Project
Design Phase 02 Controllers and Views
Lesson 1: Planning in the Project Design Phase
01 02 03 04
Project Gathering Planning the Planning for
Development Requirements Database Design Distributed
Methodologies Applications
05 02 03
Planning State Planning Planning
Management Globalization and Accessible Web
Localization Applications
Project Development Methodologies
Development
Description
Model
Waterfall Model Activities for building an application are performed sequentially in distinct phases with clear
deliverables.
Iterative Activities for building an application are performed iteratively in parts by using working
Development Model versions that are thoroughly tested, until it is finalized.
Prototype Model Activities for building an application are based on a few business requirements, and a
prototype is made. Feedback on the prototype is used as an input to develop the final
application.
Agile Development Activities for building an application are performed in rapid cycles, integrating changing
Model circumstances and requirements in the development process.
Extreme Activities for building an application begin with solving a few critical tasks. Developers test the
Programming simplified solution and obtain feedback from stakeholders to derive the detailed requirements,
which evolve over the project life cycle.
Test Driven Activities for building an application begin with a test project. Changes to the code can be
Development tested singly or as a group, throughout the project.
Unified Modeling Activities for building an application begin with UML diagrams that are used for planning and
Language documenting purposes, across all project development models.
Waterfall Model Activities for building an application are performed sequentially in distinct phases with clear
deliverables.
responds to users
• Usage scenarios
• Use cases
• User stories in the extreme programming Sample UML Use Case Diagram
methodology
Planning the Database Design
Database design in
Working with DBAs agile and extreme
programming
Planning for Distributed Applications
• Layers Browser
• Presentation
• Database
Middle Business Logic
• Communication Tier Data Access
Server
• Security
Database
Server
Planning State Management
• Cookies
• Query strings
• TempData
• Application state
• Session state
• Database tables
Planning Globalization and Localization
01 02 03
You can use the You can use resource You can use separate
internationally- files to provide a views to suit each
recognized set of localized response language code
language codes suitable to a user’s
available in browsers to culture
present content
customized to suit a
user’s language or
region
Planning Accessible Web Applications
You can ensure that your content is accessible to the broadest range of users by adhering to
the following guidelines:
• Use <div> elements and positional style sheets to lay out elements on the page
• Using diagrams
• Entity framework
Controller Action
AddPhoto (GET)
Photo AddPhoto (POST)
DisplayGallery (GET)
Logon (GET)
User
Logon (POST)
MVC Model:
Planning a logical hierarchy • Boiler
• Category
• FAQQuestion
Presenting a hierarchy in • Installation Manual
navigation controls • User Manual
57
Module Overview
01
Writing Controllers and
Actions 02 Configuring Routes
01 02 03 04 05
Responding to Writing Using Using ViewBag Demonstration:
User Requests Controller Parameters and ViewData to How to Write
Actions Pass Information Controllers and
to Views Actions
Responding to User Requests
Writing Controller Actions
01 02 03
04 05
RedirectToRoute- StatusCodeResult
Result
Return a ContentResult Object
• Routing
Using ViewBag and ViewData to Pass Information
to Views
• Models are the best way to pass data from controllers to views
• In some cases, you may want to augment the model with additional data
without modifying it
Using the ViewBag Property
• Adding Information:
• Retrieving Information:
<p>
Message is: @ViewBag.Message
</p>
<p>
Server time is: @ViewBag.ServerTime.ToString()
</p>
Demonstration: How to Write Controllers and Actions
01 02 03 04
The ASP.NET Discussion: What Is Search Configuring
Core Routing Why Add Engine Routes by Using
Engine Routes? Optimization? Convention-
Based Routing
05 06 07
Using Routes to Configuring Demonstration:
Pass Parameters Routes by Using How to Add
Attributes Routes
The ASP.NET Core Routing Engine
• Routing determines which controller and action should be called to handle a request
• Routing can be configured centrally in the Startup.cs file and locally by using attributes
Discussion: Why Add Routes?
• It is important to ensure that your web application appears at the top of the search
engine results
Configuring Routes by Using Convention-
Based Routing
• Convention-based routes might contain the following properties: name, template,
defaults, constraints and dataTokens
• Custom routes can be added as shown below:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{param}",
defaults: new { controller = "Some", action =
"ShowParam" },
constraints: new { param = "[0-9]+" });
});
You can access the values of segment variables by using one of two methods:
• It allows you to define your routes in the same file as the controller that they refer to
[Route("Some")]
public IActionResult SomeMethod()
{
return Content("Some method");
}
• Convention-based routing and attribute-based routing can be used in the same application
Demonstration: How to Add Routes
application
attribute
Lesson 3: Writing Action Filters
01 02 03
What Are Action Creating and Demonstration
Filters? Using Action : How to
Filters Create and Use
Action Filters
What Are Action Filters?
• Filters are MVC classes that can be used to manage cross-cutting concerns in your
web application
• You can apply a filter to an action by annotating the action method with an
appropriate attribute
Filter Types
Action Execution
Action Result
Conversion
}
Demonstration: How to Create and Use Action Filters
83
Module Overview
01 02 03
Adding Views Differentiating Features of the
Server-Side Code Razor Syntax
from HTML
06
04 05 Dependency
Demonstration: Alternative View Injection into
How to Use the Engines Views
Razor Syntax
Adding Views
<body>
@for (int i = 0; i < 5; i++)
{
<span>@i</span>
}
</body>
Using the @ Symbol
You can:
• You can inject a service into a view using the @inject directive
01 02 03 04 05
Introduction to Using HTML Action Demonstration: Using Tag Helpers Demonstration:
HTML Helpers and Helpers How to Use How to Use Tag
Tag Helpers HTML Helpers Helpers
Introduction to HTML Helpers and Tag Helpers
HTML helpers:
• Use a Razor syntax
• Make it easier to identify areas of code
• Does not require explicit enabling of the feature
Tag helpers:
• Use an HTML-like syntax, as well as tag properties
• Require explicit usage of a directive
• Create more easily legible HTML with less immediately apparent code
Using HTML Action Helpers
Html.ActionLink()
<a href="/photo/display/1">
Click here to view photo 1
</a>
Url.Action()
<img alt="This image came from an action"
src="@Url.Action("GetImage", new { id = 1 })" />
<img
alt="This image came from an action"
src="/photo/getimage/1" })"
/>
Demonstration: How to Use HTML Helpers
HTML helper:
Tag helper:
• To use tag helpers, you need to add the @addTagHelper directive to a view
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
• To make tag helper available to all views, add the @addTagHelper directive
to the _ViewImports.cshtml file
Demonstration: How to Use Tag Helpers
01 02 03 04
Creating Partial Using Partial Demonstration: Creating View
Views Views How to Create Components
and Use Partial
Views
05 06 07
Using View Invoking View Demonstration:
Components Components with How to Create and
Parameters Use View
Components
Creating Partial Views
• Use partial views to render identical HTML content in different locations of your web
application
• Often created inside the /Views/Shared folder
• By convention, the names of partial views are prefixed with an underscore
For example:
_MyPartialView.cshtml
@await Html.PartialAsync("_MyPartialView")
Now in main view
@await Html.PartialAsync("_MyPartialView")
In partial view
Now in main view
In partial view
Demonstration: How to Create and Use Partial Views
• You can use view components to render identical or similar HTML content in different
locations
• A class
• A view
• The name of the folder should be the same as the name of the view component class
without the ViewComponent suffix
A View Component Example
some text
Using View Components
@await Component.InvokeAsync("My")
some text
<vc:My></vc:My>
some text
Invoking View Components with Parameters
@await Component.InvokeAsync("My", 5)
Demonstration: How to Add View Component
112
Module Overview
Validating MVC
03 Application
Lesson 1: Creating MVC Models
01 02 03
Developing Passing Models Binding Views to
Models to Views Model Classes
and Displaying
Data
06
04 05 Adding CRUD
Demonstration: What Are Model Operations to
How to Bind Binders? Controllers
Views to Model
Classes
Developing Models
The instances of model classes are usually created in a controller and passed to a view
Passing a Model to the Display View
@EditorForModel
Demonstration: How to Bind Views to Model Classes
logic:
• The binder examines the definition of the action that it must pass
parameters to
• The binder searches for values in the request that can be passed
as parameters
Passing Parameters to Actions
Person
FirstName=James
LastName=Smith
[HttpPost]
public IActionResult GetName(Person person)
Adding CRUD Operations to Controllers
01 02 03
Using Display and Using Display Using Editor
Edit Data Helpers Helpers
Annotations
04 05
Using Form Helpers Demonstration:
How to Use Display
and Edit Data
Annotations
Using Display and Edit Data Annotations
[DataType(DataType.MultilineText)]
public string Description { get; set; }
}
@EditorForModel
Using Display Helpers
• Html.DisplayNameFor()
First Name:
• Html.DisplayFor()
James
Using Editor Helpers
• Html.LabelFor()
<label for="ContactMe">
Contact Me
</label>
• Html.EditorFor()
<input type="checkbox"
name="ContactMe" />
Using Editor Helpers (Continued)
• LabelTagHelper
<label asp-for="ContactMe"></label>
<label for="ContactMe">
Contact Me
</label>
• InputTagHelper
<input type="checkbox"
name="ContactMe" />
Using Form Helpers
Html.BeginForm
@using (Html.BeginForm("ShowDetails",
"Person"))
{
}
<form
action="/Person/ShowDetails"
method="post“>
</form>
FormTagHelper
<form asp-controller="Person"
asp-action="ShowDetails">
</form>
Demonstration: How to Use Display and Edit Data
Annotations
01 02 03
Validating User Using Validation Demonstration:
Input with Data Helpers How to Validate
Annotations User Input with
Data Annotations
04 05
Adding Custom Demonstration:
Validations How to Add
Custom Validations
Validating User Input with Data Annotations
[Range(0, 150)]
public int Age { get; set; }
[Required]
[RegularExpression(".+\\@.+\\..+")]
public string EmailAddress { get; set; }
[DataType(DataType.MultilineText)]
[StringLength(20)]
public string Description { get; set; }
}
Using Validation Helpers
• Html.ValidationSummary()
@Html.ValidationSummary()
<ul>
<li>Please enter a name.</li>
<li>The EmailAddress field is required</li>
</ul>
• Html.ValidationMessageFor()
• ValidationSummaryTagHelper
<div asp-validation-summary=“All”></div>
<ul>
<li>Please enter a name.</li>
<li>The EmailAddress field is required</li>
</ul>
• ValidationMessageTagHelper
<span asp-validation-for=“Name”></span>
140
Module Overview
01 02 03
Connecting to a Object Relational Overview of Entity
Database Using Mapper (ORM) Framework
ADO.NET
04 05
Discussion: Choose Database Providers
between Entity
Framework Core
and Entity
Framework 6
Connecting to a Database Using ADO.NET
return View();
}
}
Object Relational Mapper (ORM)
• Database First
• Model First
• Code First
Which Entity Framework version will you use in the following scenarios?
Application
Request sent to Response from
database provider database provider
with application with application
language language
Database Provider
Request sent to Response from
database with the the database with
database database
language language
Database
Lesson 2: Working with Entity Framework Core
01 02 03
Using an Entity Using LINQ to Loading Related
Framework Entities Data
Context
04 05
Manipulating Demonstration:
Data by Using How to Use
Entity Entity
Framework Framework Core
Using an Entity Framework Context
An entity:
• LINQ to Entities is the version of LINQ that works with Entity Framework
which include:
• Explicit loading
• Eager loading
• Lazy loading
Loading Related Data by using Explicit Loading
_context.Entry(city)
.Collection(c => c.People)
.Load();
_context.Entry(city)
.Reference(c => c.Country)
.Load();
return View(city);
}
Loading Related Data by using Eager Loading
return View(countries);
}
Loading Related Data by using Lazy Loading
services.AddDbContext<DemographyContext>(
options => options.UseLazyLoadingProxies()
.UseSqlite("Data Source=example.db"));
Manipulating Data by Using Entity Framework
_context.People.Remove(person);
_context.SaveChanges();
Demonstration: How to Use Entity Framework Core
01 02 03
Connecting to Configuration in Specifying a
Microsoft SQL ASP.NET Core Connection
Server String in a
Configuration File
04 05 06
The Repository Demonstration: Using Migrations
Pattern How to Apply the
Repository
Pattern
Connecting to Microsoft SQL Server
The UseSqlServer method configures the Entity Framework context to connect to a SQL
Server database
• Environment variables
• Custom provider
• And more…
Specifying a Connection String in a
Configuration File
• Connection string in a configuration file:
{
"ConnectionStrings": {
"DefaultConnection": "..."
}
}
string connectionString =
_configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<HrContext>(options =>
options.UseSqlServer(connectionString));
The Repository Pattern
Demonstration: How to Apply the Repository Pattern
repository to a controller
database
• Add a migration:
• Add-Migration <name_of_the_migration>
• Update-Database
Module 6 Lab: Using Entity
Framework Core in ASP.NET Core
Labs And Exercises
Module Review
and Takeaways
Module 07
Using Layouts, CSS and JavaScript in ASP.NET
Core MVC
169
Module Overview
03 Using jQuery
Lesson 1: Using Layouts
01 02 03
What are Layouts? Creating a Layout Linking Views and
Layouts
04 05
Using Sections in a Demonstration:
Layout How to Create a
Layout and Link it
to a View
What are Layouts?
Layout
\Views\Shared folder
An example of a layout:
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
Linking Views and Layouts
• You can add the Layout directive at the top of the view file
@RenderSection("section1")
@RenderBody()
@RenderSection("section2", false)
@section section1
{
<div>This is section1 content</div>
}
<div>This is the body</div>
Demonstration: How to Create a Layout and Link it to
a View
01 02 03 04
Importing Styles Rendering and Using External Demonstration:
Executing Libraries How to Use npm to
JavaScript Code Add a Library
Importing Styles
• You should modify the layout of the web application by using the <link>
element
• You can add CSS selectors to define how the styles should be applied:
• CSS id selector helps specify a style for any unique element in the
HTML code
.menu
{
font-weight:bold; <p class="menu"> this is menu</p>
}
Rendering and Executing JavaScript Code
<script>
function helloWorld() {
alert('Hello World');
}
</script>
<script>
helloWorld()
</script>
Use a Package
Download the Use a CDN Manager
source files (Content • NuGet – For
from an Delivery server-side
official source Network) libraries
• Yarn
• Webpack
• Bower
• npm
Using npm to Add Libraries
To start using NPM in an ASP.NET Core application, you should add a package.json file to your solution in
your project’s root folder:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"dependencies": {
"jquery": "3.3.1"
},
"devDependencies": {
}
}
Demonstration: How to Use npm to Add a Library
01 02 03
Introduction to Accessing HTML Modifying HTML
jQuery Elements by using Elements by using
jQuery jQuery
04 05 06
Demonstration: Calling a Server by Client-Side
How to Modify using jQuery Validation by using
HTML Elements by jQuery
using jQuery
Introduction to jQuery
• jQuery files:
$(function() {
$.each([4, 9], function(index, value) {
alert(index + ":" + value);
});
});
Accessing HTML Elements by using jQuery
• You can use the following selector to select elements by element name, id,
or CSS class:
$(element name|#id|.class)
$("#hello").click(function(event) {
alert("Hello World");
});
Modifying HTML Elements by using jQuery
• Immediate validation
• Less secure
• Easy to bypass
validation
196
Module Overview
03 Responsive Design
Lesson 1: Applying Styles
01 02 03
Introduction to Bootstrap Demonstration:
Bootstrap Components How to Work with
Bootstrap
04 05
Styling Applications Styling Applications
with Sass with Less
Introduction to Bootstrap
What is Boostrap?
To get started with bootstrap you need to add a few files to your application:
• popper.js – This library is responsible for the HTML elements that pop out
"dependencies": {
"bootstrap": "4.1.3",
"jquery": "3.3.1",
"popper.js": "1.14.3"
}
Bootstrap Components
<ul class="nav">
<li class=“nav-item”>
<a class="nav-link active" href=“/">Home</a>
</li>
<li class=“nav-item”>
<a class="nav-link" href=“/home/about">About</a>
</li>
</ul>
Demonstration: How to Work with Bootstrap
$highlights: #00FFFF;
.p {
color: $highlights;
font-size: 16px;
span {
color: darken($highlights, 20%);
em {
text-decoration: underline;
}
}
}
Styling Applications with Less
@highlights: #00FFFF;
.p {
color: @highlights;
font-size: 16px;
span {
color: darken(@highlights, 20%);
em {
text-decoration: underline;
}
}
}
Lesson 2: Using Task Runners
01 02 03 04
Using Grunt Using gulp Demonstration: Bundling and
How to Use gulp to Minification
Compile Sass to
CSS
Using Grunt
compilation
• Sections of Grunfile.js:
module.exports = function(grunt) {
grunt.initConfig({
sass: {
dist: {
files: [{
expand: true,
cwd: 'Styles',
src: ['**/*.scss'],
dest: 'wwwroot/styles',
ext: '.css'
}]
}
}
});
grunt.loadNpmTasks("grunt-sass");
};
Using gulp
pipeline
var paths = {
webroot: "./wwwroot/"
};
paths.sass = "./Styles/*.scss";
paths.compiledCss = paths.webroot + "styles/";
gulp.task("sass", function() {
return gulp.src(paths.sass)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(paths.compiledCss));
});
Multiple Tasks in gulp
gulp.task("one", function() {
console.log("one");
});
gulp.task("two", function() {
console.log("two");
});
gulp.task("three", function() {
console.log("three");
});
and minification
added:
gulp.task("minify-js", function() {
return gulp.src(paths.jsFiles)
.pipe(concat(paths.minifiedJsFileName))
.pipe(uglify())
.pipe(gulp.dest(paths.destinationJsFolder));
});
gulp.task("js-watcher", function() {
gulp.watch(paths.jsFiles, ["minify-js"]);
});
Lesson 3: Responsive Design
01 02 03
The HTML5 CSS Media Queries The Bootstrap Grid
Viewport Attribute System
04 05
Demonstration: Applying the
How to Use the Flexbox Layout
Bootstrap Grid
System
The HTML5 Viewport Attribute
The viewport attribute helps render webpages in a virtual window in mobile devices
<div class="container">
<div class="row">
<div class="col">
<h3>First Column</h3>
</div>
<div class="col">
<h3>Second Column</h3>
</div>
</div>
</div>
Demonstration: How to Use the Bootstrap Grid
System
• It provides an efficient way to layout and align items inside a specific parent
container
• Using display: flex a parent container can alter its children items width, height
• Each direct child inside the flex container can override the behavior specified by
Parent container
Child item
Using Flexbox
.container {
display: flex; <div class="container">
justify-content: center; <div class="box box-1">01</div>
align-items: center; <div class="box box-2">02</div>
<div class="box box-3">03</div>
height: 800px;
background-color: gray; <div class="box box-4">04</div>
padding: 20px; </div>
}
.box {
width: 100px;
}
.box-4 {
order: -1;
align-self: flex-start;
}
.box-2 {
flex-grow: 2;
}
Module 08 Lab: Client-
Side Development
Labs and Tasks
Module Review
and Takeaways
Module 9
Testing and Troubleshooting
Module Overview
Implementing an
01 Testing MVC Applications 02 Exception Handling
Strategy
01 02 03
Why Perform Unit Principles of Test- Writing Loosely
Tests? Driven Coupled MVC
Development Components
04 05 06
Writing Unit Tests Demonstration: Using Mocking
for MVC How to Run Unit Frameworks
Components Tests
Why Perform Unit Tests?
• Types of Tests:
• Unit tests
• Integration tests
• Acceptance tests
• Arrange. This phase of a unit test arranges data to run the test on
• Act. This phase of the unit test calls the methods you want to test
• Assert. This phase of the unit test checks that the results are as
expected
• Any unit test that fails is highlighted in Visual Studio whenever you
run the test or debug the application
▪ Understand the
problem
▪ Specify the
desired
behavior
▪ Run the test
▪ Test fails
coupling
Writing Unit Tests for MVC Components
01
application project by adding a test
project to the solution
[TestMethod]
public void IndexModelShouldBeListOfProducts()
{
// Arrange
var productRepository = new FakeProductRepository();
// Act
var result = productController.Index() as ViewResult;
// Assert
Assert.AreEqual(typeof(List<Product>), result.Model.GetType());
}
Demonstration: How to Run Unit Tests
unit tests
Lesson 2: Implementing an Exception
Handling Strategy
01 02 03 04
Raising and Working with Configuring Error Demonstration:
Catching Multiple Handling How to Configure
Exceptions Environments Exception Handling
Raising and Catching Exceptions
• The most common method to catch an exception is to use the try/catch block
• IsDevelopment
• IsStaging
• IsProduction
• IsEnvironment(*Environment Name*)
Using Environments in Views
Use the environment tag helper to differentiate between environments inside views
<environment include="Development">
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/popper.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
</environment>
<environment include="Production,Staging">
<script src="~/Scripts/vendor.min.js"></script>
</environment>
Configuring Error Handling
01 02 03
Logging Exceptions Logging in ASP.NET Demonstration:
Core How to Log an MVC
Application
Logging Exceptions
Live Web
Application
Administrator
Error
User
Database
When an exception occurs, the application sends an email message to the administrators,
and logs full details of the exception to a database.
Logging in ASP.NET Core
250
Module Overview
Authorization in
01
Authentication in
ASP.NET Core 02 ASP.NET Core
01 02 03
The Need for Setting up Interfacing with
Authentication ASP.NET Core ASP.NET Core
Identity Identity
04 05 06
ASP.NET Core Demonstration: Customizing
Identity How to use Providers with
Configuration ASP.NET Core ASP.NET Core
Identity
The Need for Authentication
To help prevent
To ensure malicious activities
connected users on your
use the correct application or
credentials website
Multi Factor
Setting up ASP.NET Core Identity
01 02 03 04
It requires an It requires It requires a call It requires a call
Identity class IdentityDbConte to to
inheriting from xt which is used AddDefaultIdent UseAuthentication
IdentityUser for all database ity in in Configure
communications ConfigureServic
es
Program.cs Configurations for Adding Authentication
builder.Services.AddDefaultIdentity<IdentityUser>(
options => options.SignIn.RequireConfirmedAccount = false
).AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
ASP.NET Core Identity Configuration
There are many things you can configure in ASP.NET Core Identity configuration:
User settings –
01 Allow to configure what constitutes a legal username and other options
Lockout settings –
02 Allow to customize lockout behavior if incorrect passwords are supplied
Password settings –
03 Allow setting password complexity rules
Sign in settings –
04 Allow requiring additional methods of authentication before creating users
Cookie settings –
05 Allow changing the behavior of cookies on the website
Demonstration: How to use ASP.NET Core Identity
• By default, ASP.NET Core Identity uses Entity Framework and the built-in authentication
logic
• You can extend Identity to allow authentication from multiple external sources
• You are also able to use Windows Active Directory to handle authentication for you, to
prevent external users from accessing your application
• Furthermore, the backend can be fully customized to use any form of storage you require,
as long as it can be used in an ASP.NET Core application
Lesson 2: Authorization in ASP.NET Core
01 02 03
Introduction to Authorization Demonstration:
Authorization Options How to Authorize
Access to
Controller
Actions
Introduction to Authorization
There are many different ways to block users from accessing resources.
• Set up authorization
01 02 03
Cross-Site Cross-Site SQL Injection
Scripting Request Forgery
04 05
Cross-Origin Secure Sockets
Requests Layer
Cross-Site Scripting
• Utilize ValidateAntiForgeryToken or
AutoValidateAntiForgeryToken to protect
actions on your controllers
modifications
Cross-Origin Requests
By default your server You can enable it and Enabling CORS can
will not accept any utilize CORS policies to create a risk within
cross-origin requests create conditions under applications and needs
from external sources. which your application to be handled with
content will be care. It is important to
accessible to external create policies as
applications. specific as required.
Secure Sockets Layer
SSL:
01 02 03 04
Encrypt Decrypt Ensure Certify
Implementing a
01 Caching Strategy in 02 Managing State
ASP.NET Core
Lesson 1: Implementing a Caching Strategy
01 02 03
Why Use Cache Tag Helper Demonstration:
Caching? How to Configure
Caching
04 05
The Data Cache Distributed
Cache
Why Use Caching?
Caching:
• enabled
• priority
<cache>
@for (int i = 0; i < DateTime.Now.Second; i++)
{
<div>Number of seconds</div>
}
</cache>
<cache vary-by="@Model.Id">
<div>
@Model.Name
</div>
<div>
@Model.Price
</div>
</cache>
Demonstration: How to Configure Caching
return View(products);
}
Distributed Cache
Distributed cache:
01 02 03
Why Store State State Storage Configuring
Information? Options Session State
04 05
Demonstration: Using the HTML5
How to Store and Web Storage API
Retrieve State
Information
Why Store State Information?
Using states:
State Storage:
• Allows websites to maintain a more coherent continuous
experience
• Involves client-side session management techniques
such as:
• Hidden fields
• Cookies
• Query strings
• Involves server-side session management techniques
such as:
• TempData
• HttpContext.Items
• Cache
• Dependency Injection
• Session state
TempData Example
if (tempDataValue != null)
{
return Content("TempData exists!" + tempDataValue);
}
Types of storage:
01 02 03
HTTP Services HTTP Messages Status Codes
04 05
Introduction to What is a Web
Web API API?
HTTP Services
parallel to HTTP
Accept-Language: en-US,en;q=0.7,he;q=0.3
Host: localhost:4392
DNT: 1
Connection: Keep-Alive
An HTTP Response Message
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Tue, 13 Nov 2012 18:05:11 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 188
Connection: Close
{"TravelerId":1,"TravelerUserIdentity":"aaabbbccc","
FirstName":“John","LastName":“Doe","MobilePhone":
"555-555-5555","HomeAddress":“123 Main
Street","Passport":"AB123456789"}
Status Codes
released
What is a Web API?
Web API:
• Helps create REST-style APIs
application
Request
Response
Lesson 2: Developing a Web API
01 02 03 04
Using Routes and RESTful Services Action Methods Binding
Controllers and HTTP Verbs Parameters to
Request Message
05 06 07
Control the HTTP Data Return Demonstration:
Response Formats How to Develop
a Web API
Using Routes and Controllers
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
public string Get()
{
return "Response from Web API";
}
}
RESTful Services
• Uses HTTP verbs to identify the operation that the application needs to
perform. The HTTP verbs include:
• GET
• POST
• PUT
• DELETE
A Rest Service Example
[Route("api/[controller]")]
public class CustomerController : ControllerBase
{
public IEnumerable<Customer> Get()
{}
public void Post(Customer item)
{}
public void Put(int id, Customer item)
{}
public void Delete(int id)
{}
}
Action Methods and HTTP Verbs
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
[HttpGet("Some")]
public string SomeMethod()
{
return "SomeMethod was invoked";
}
[HttpGet("Other")]
public string OtherMethod()
{
return "OtherMethod was invoked";
}
}
Binding Parameters to Request Message
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
[HttpGet("{id}/{name}")]
public string Get(int id, string name)
{
return "id: " + id + ", name: " + name;
}
}
• This action method is chosen when sending a GET request by using the
api/Home/1/Mike path
Using the ApiController Attribute
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
[HttpPost]
public void Post(Customer item)
{}
}
Control the HTTP Response
HTTP responses use status codes to express the outcome of the request
processing
return Ok(_items[id]);
}
Return ActionResult<T>
return _items[id];
}
Data Return Formats
JSON XML
["value1","value2"]
<ArrayOfstring>
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
Demonstration: How to Develop a Web API
01 02 03 04 05
Calling Web APIs Demonstration: Calling Web APIs Working with Demonstration:
by Using jQuery How to call Web by using Server- Complex Objects How to Call Web
Code APIs by Using Side Code APIs by Using
jQuery code Server-Side Code
Calling Web APIs by Using jQuery Code
$(function() {
$.ajax({
url: "http://localhost:[port]/api/values/key1",
type: "GET"
}).done(function (responseText) {
$("#myDiv").text(responseText);
}).fail(function () {
alert("An error has occurred");
});
});
Calling the Web API Post method by using
jQuery
$(function() {
var params = { key: 'key3', value: 'value3' };
$.ajax({
url: "http://localhost:[port]/api/values",
type: "POST",
data: JSON.stringify({ key: 'key3', value: 'value3' }),
contentType: "application/json;charset=utf-8"
}).done(function (responseText) {
$("#myDiv").text("Value added successfully");
}).fail(function () {
alert("An error has occurred");
});
});
Demonstration: How to call Web APIs by Using jQuery
code
HttpClient client =
_httpClientFactory.CreateClient();
client.BaseAddress = new
Uri("http://localhost:[port]");
HttpResponseMessage response =
client.GetAsync("api/Values/key1").Result;
Working with Complex Objects
OBJECT
OBJECT
Get a Complex Object from a Web API
HttpResponseMessage response =
await httpClient.GetAsync("api/Person");
if (response.IsSuccessStatusCode)
{
Person person =
await response.Content.ReadAsAsync<Person>();
return Content(person.Name);
}
else
{
return Content("An error has occurred");
}
Pass a Complex Object to a Web API
Entry entry =
new Entry() { Key = "key3", Value = "value3" };
HttpResponseMessage response =
await httpClient.PostAsJsonAsync("api/Values", entry);
if (response.IsSuccessStatusCode)
{
return Content("succedded");
}
else
{
return Content("An error has occurred");
}
Demonstration: How to Call Web APIs by
Using Server-Side Code
Microsoft Azure
03 Fundamentals
Lesson 1: On-Premises Hosting and Deployment
01 02 03 04
Web Servers Hosting ASP.NET Deploying to IIS File Providers
Core Application
Web Servers
Setting up the server is an important part of an ASP.NET Core MVC application and requires
you to make important decisions
01 02
By choosing Kestrel, you get: By choosing HTTP.sys you get:
publishing process
application
application
• Set up IIS
• After the first deployment you can directly perform the deployment
File Providers
File Providers allow us to interact with actual files in the project structure:
interacts with files that are interacts with files which allows us to combine two
physically present in the are embedded within the or more providers and use
project structure application itself, allowing them all with a single
for added security at the interface
cost of being
unchangeable at run time
Lesson 2: Deployment to Microsoft Azure
01 02 03
What is Microsoft Benefits of Deploying Web
Azure? Hosting in Application on
Microsoft Azure Microsoft Azure
04 05 06
Demonstration: Azure Debugging a
How to Deploy a Deployment Microsoft Azure
Web Application Strategy Application
to Microsoft
Azure
What is Microsoft Azure?
Infrastructure-as-a-Service Platform-as-a-Service
Benefits of Azure:
Efficiency
• With PaaS, deploying and scaling
application is very easy. This leads to
efficient use or resources. Elasticity
• Ability to scale up to thousands of
machines
Security
• Common compliances and certifications
in place. Also provides DDoS
protection, threat protection, and
information protection. Cost
• Pay as you use model means no up-
front investment needed and hence
Developer Tools more cost-effective.
• A wide variety of tools available for
building and deploying your application
automatically.
Deploying Web Application on Microsoft Azure
• PaaS from Microsoft Azure, provides a managed platform to deploy and host your
applications
• App Service provides easy integration to other Azure services such as Storage, Active
Directory etc.