2023 Lecture Notes of Web Technology
with .NET
Web Technology with
.NET
C# Features
Dharmendra Bhatti 1
C# Features
Dharmendra Bhatti 2
Prof. (Dr.) Dharmendra Bhatti 1
2023 Lecture Notes of Web Technology
with .NET
Creating the Example Project
ldotnet new globaljson --sdk-version 7.0 --
output LanguageFeatures
ldotnet new web --no-https --output
LanguageFeatures --framework net7.0
ldotnet new sln -o LanguageFeatures
ldotnet sln LanguageFeatures add
LanguageFeatures
Dharmendra Bhatti 3
Opening the Project
lIf you are using Visual Studio, select File
➤ Open ➤ Project/Solution, select the
LanguageFeatures.sln
lIf you are using Visual Studio Code, select
File ➤ Open Folder, navigate to the
LanguageFeatures folder, and click the
Select Folder button.
Dharmendra Bhatti 4
Prof. (Dr.) Dharmendra Bhatti 2
2023 Lecture Notes of Web Technology
with .NET
Enabling the MVC Framework
l// Enabling MVC in the Program.cs File in
the LanguageFeatures Folder
lvar builder =
WebApplication.CreateBuilder(args);
lbuilder.Services.AddControllersWithVie
ws();
lvar app = builder.Build();
Dharmendra Bhatti 5
Enabling the MVC Framework
l// Enabling MVC in the Program.cs File in
the LanguageFeatures Folder
lvar app = builder.Build();
l//app.MapGet("/", () => "Hello World!");
lapp.MapDefaultControllerRoute();
lapp.Run(); Dharmendra Bhatti 6
Prof. (Dr.) Dharmendra Bhatti 3
2023 Lecture Notes of Web Technology
with .NET
Creating the Data Model
l// Add a folder called Models and create a
class file called Product.cs within it
Dharmendra Bhatti 7
Creating the Controller and View
l// Create a Controllers folder in project and
added to it a class file called
HomeController.cs
Dharmendra Bhatti 8
Prof. (Dr.) Dharmendra Bhatti 4
2023 Lecture Notes of Web Technology
with .NET
Creating the Controller and View
l// Create a Views/Home folder in project
and add a Razor View called Index.cshtml
l
Dharmendra Bhatti 9
Running the Example Application
ldotnet run
Dharmendra Bhatti 10
Prof. (Dr.) Dharmendra Bhatti 5
2023 Lecture Notes of Web Technology
with .NET
Global using Statements
l// Adding a using Statement in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 11
Global using Statements
lIn most projects, some namespaces are
required throughout the application, such
as those containing data model classes.
lThis can result in a long list of using
statements, duplicated in every code file.
lGlobal using statements address this
problem by allowing using statements for
commonly required namespaces to be
defined in a single location.
Dharmendra Bhatti 12
Prof. (Dr.) Dharmendra Bhatti 6
2023 Lecture Notes of Web Technology
with .NET
Global using Statements
l// Add a code file named GlobalUsings.cs
to the LanguageFeatures project
lglobal using LanguageFeatures.Models;
lglobal using Microsoft.AspNetCore.Mvc;
Dharmendra Bhatti 13
Global using Statements
l// Remove using Statements in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 14
Prof. (Dr.) Dharmendra Bhatti 7
2023 Lecture Notes of Web Technology
with .NET
Null State Analysis
lCompiler identifies attempts to access
references that may be unintentionally
null, preventing null reference exceptions
at runtime
Dharmendra Bhatti 15
A null state analysis warning
Dharmendra Bhatti 16
Prof. (Dr.) Dharmendra Bhatti 8
2023 Lecture Notes of Web Technology
with .NET
nullable
lC# variables are divided into two groups:
nullable and non- nullable.
lnullable variables can be null, which will
trigger a NullReferenceException.
lnon-nullable variables can never be null
Dharmendra Bhatti 17
nullable
lA question mark (the ? character) is
appended to a type to denote a nullable
type.
li.e. a variable’s type is string?
Dharmendra Bhatti 18
Prof. (Dr.) Dharmendra Bhatti 9
2023 Lecture Notes of Web Technology
with .NET
nullable
lThe most common issues are
¡attempting to assign null to non-nullable
variables and
¡attempting to access members defined by
nullable variables without checking to see if
they are null
Dharmendra Bhatti 19
Ensuring Fields and Properties Are
Assigned Values
l// Assign default value to non-nullable type
l// P roviding a Default Value in the
Product.cs File in the Models Folder
Dharmendra Bhatti 20
Prof. (Dr.) Dharmendra Bhatti 10
2023 Lecture Notes of Web Technology
with .NET
Using Nullable Types
lThere is a mismatch between the type
used for the result of the GetProducts
method and the values that are used to
initialize it:
l...
lreturn new Product[ ] { kayak, lifejacket,
null };
l...
Dharmendra Bhatti 21
Using Nullable Types
Dharmendra Bhatti 22
Prof. (Dr.) Dharmendra Bhatti 11
2023 Lecture Notes of Web Technology
with .NET
Using Nullable Types
lA variable of type Product?[ ] denotes an
array that can contain Product or null
values but that won’t be null itself:
l...
lProduct?[ ] arr1 = new Product?[ ] { kayak,
lifejacket, null }; // OK
lProduct?[ ] arr2 = null; // Not OK
l...
Dharmendra Bhatti 23
Using Nullable Types
lA variable of type Product[ ]? is an array
that can hold only Product values and not
null values, but the array itself may be null:
l...
lProduct[ ]? arr1 = new Product?[ ] { kayak,
lifejacket, null }; // Not OK
lProduct[ ]? arr2 = null; // OK
l...
Dharmendra Bhatti 24
Prof. (Dr.) Dharmendra Bhatti 12
2023 Lecture Notes of Web Technology
with .NET
Using Nullable Types
lA variable of type Product?[ ]? is an array
that can contain Product or null values and
that can itself be null:
l...
lProduct?[ ]? arr1 = new Product?[ ] {
kayak, lifejacket, null }; // OK
lProduct?[ ]? arr2 = null; // Also OK ...
Dharmendra Bhatti 25
Checking for Null Values
l// Change the type of the products variable
to match the type returned by the
GetProducts method
l// Change Type in the HomeController.cs
File in the Controllers Folder
Dharmendra Bhatti 26
Prof. (Dr.) Dharmendra Bhatti 13
2023 Lecture Notes of Web Technology
with .NET
Checking for Null Values
lThe statement flagged by the compiler
attempts to access the Name field of the
element at index zero in the array, which might
be null since the array type is Product?[ ]
Dharmendra Bhatti 27
Checking for Null Values
l// Guarding Against a null Value in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 28
Prof. (Dr.) Dharmendra Bhatti 14
2023 Lecture Notes of Web Technology
with .NET
Using the Null Conditional Operator
l// Using the Null Conditional Operator in
the HomeController.cs File in the
Controllers Folder
Dharmendra Bhatti 29
Using the Null-Coalescing Operator
l// Using the Null-Coalescing Operator in
the HomeController.cs File in the
Controllers Folder
Dharmendra Bhatti 30
Prof. (Dr.) Dharmendra Bhatti 15
2023 Lecture Notes of Web Technology
with .NET
Overriding Null State Analysis
l// Using the Null-Forgiving Operator in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 31
Overriding Null State Analysis
lThe null-forgiving operator is an
exclamation mark and is used in this
example to tell the compiler that
products[0] isn’t null, even though null
state analysis has identified that it might
be null.
Dharmendra Bhatti 32
Prof. (Dr.) Dharmendra Bhatti 16
2023 Lecture Notes of Web Technology
with .NET
Using String Interpolation
lC# supports string interpolation to create
formatted strings, which uses templates
with variable names that are resolved and
inserted into the output
Dharmendra Bhatti 33
Using String Interpolation
l// Using String Interpolation in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 34
Prof. (Dr.) Dharmendra Bhatti 17
2023 Lecture Notes of Web Technology
with .NET
Using String Interpolation
lC# supports string interpolation to create
formatted strings, which uses templates
with variable names that are resolved and
inserted into the output
Dharmendra Bhatti 35
Using String Interpolation
lInterpolated strings are prefixed with the $
character and contain holes, which are
references to values contained within the {
and } characters.
lWhen the string is evaluated, the holes are
filled in with the current values of the
variables or constants that are specified.
Dharmendra Bhatti 36
Prof. (Dr.) Dharmendra Bhatti 18
2023 Lecture Notes of Web Technology
with .NET
Using String Interpolation
lString interpolation supports the string
format specifiers, which can be applied
within holes, so $"Price: {price:C2}" would
format the price value as a currency value
with two decimal digits
Dharmendra Bhatti 37
Using Object and Collection
Initializers
lObject Initializer
Dharmendra Bhatti 38
Prof. (Dr.) Dharmendra Bhatti 19
2023 Lecture Notes of Web Technology
with .NET
Using Object and Collection
Initializers
lCollection Initializer
Dharmendra Bhatti 39
Using Object and Collection
Initializers
lIndex Initializers
Dharmendra Bhatti 40
Prof. (Dr.) Dharmendra Bhatti 20
2023 Lecture Notes of Web Technology
with .NET
Using Target-Typed New
Expressions
Dharmendra Bhatti 41
Pattern Matching
lThe “is” keyword performs a type check
and, if a value is of the specified type, will
assign the value to a new variable
Dharmendra Bhatti 42
Prof. (Dr.) Dharmendra Bhatti 21
2023 Lecture Notes of Web Technology
with .NET
Pattern Matching
lPattern Matching in switch Statements
Dharmendra Bhatti 43
Using Extension Methods
lExtension methods are a convenient way
of adding methods to classes that you
cannot modify directly, typically because
they are provided by Microsoft or a third-
party package.
Dharmendra Bhatti 44
Prof. (Dr.) Dharmendra Bhatti 22
2023 Lecture Notes of Web Technology
with .NET
Using Extension Methods
l// ShoppingCart.cs File in the Models
Folder
Dharmendra Bhatti 45
Using Extension Methods
l// MyExtensionMethods.cs File in the
Models Folder
Dharmendra Bhatti 46
Prof. (Dr.) Dharmendra Bhatti 23
2023 Lecture Notes of Web Technology
with .NET
Using Extension Methods
lExtension methods are defined in static
classes within the same namespace as
the class to which the extension methods
applies.
Dharmendra Bhatti 47
Using Extension Methods
l// Applying an Extension Method in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 48
Prof. (Dr.) Dharmendra Bhatti 24
2023 Lecture Notes of Web Technology
with .NET
Applying Extension Methods to an
Interface
l// Implementing an Interface in the
ShoppingCart.cs File in the Models Folder
Dharmendra Bhatti 49
Applying Extension Methods to an
Interface
l// Updating an Extension Method in the
MyExtensionMethods.cs File in the Models
Folder
Dharmendra Bhatti 50
Prof. (Dr.) Dharmendra Bhatti 25
2023 Lecture Notes of Web Technology
with .NET
Applying Extension Methods to an
Interface
l// Applying an Extension Method in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 51
Creating Filtering Extension Methods
l// A Filtering Extension Method in the
MyExtensionMethods.cs File in the Models
Folder
Dharmendra Bhatti 52
Prof. (Dr.) Dharmendra Bhatti 26
2023 Lecture Notes of Web Technology
with .NET
Creating Filtering Extension Methods
Dharmendra Bhatti 53
Creating Filtering Extension Methods
l// Using the Filtering Extension Method in
the HomeController.cs File in the
Controllers Folder
Dharmendra Bhatti 54
Prof. (Dr.) Dharmendra Bhatti 27
2023 Lecture Notes of Web Technology
with .NET
Using Lambda Expressions
lLambda expressions in C# are used like
anonymous functions, with the difference
that in Lambda expressions you don't
need to specify the type of the value that
you input thus making it more flexible to
use.
lThe '=>' is the lambda operator which is
used in all lambda expressions.
Dharmendra Bhatti 55
Using Lambda Expressions
lThe expression num => num * 5 is a
lambda expression.
lThe => operator is called the "lambda
operator".
lIn this example, num is an input parameter
to the anonymous function, and the return
value of this function is num * 5 .
lSo when multiplyByFive is called with a
parameter of 7 , the result is 7 * 5 , or 35 .
Dharmendra Bhatti 56
Prof. (Dr.) Dharmendra Bhatti 28
2023 Lecture Notes of Web Technology
with .NET
Using Lambda Expressions
l// Adding second Filter Method in the
MyExtensionMethods.cs File in the Models
Folder
Dharmendra Bhatti 57
Using Lambda Expressions
l// Using Two Filter Methods in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 58
Prof. (Dr.) Dharmendra Bhatti 29
2023 Lecture Notes of Web Technology
with .NET
Using Lambda Expressions
lCreating a General Filter Method in the
MyExtensionMethods.cs File in the Models
Folder
Dharmendra Bhatti 59
Using Lambda Expressions
l// Using a Function to Filter Objects in the
HomeController.cs File in the Controllers
Dharmendra Bhatti 60
Prof. (Dr.) Dharmendra Bhatti 30
2023 Lecture Notes of Web Technology
with .NET
Using Lambda Expressions
Dharmendra Bhatti 61
Using Lambda Expressions
l// Using a Lambda Expression in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 62
Prof. (Dr.) Dharmendra Bhatti 31
2023 Lecture Notes of Web Technology
with .NET
Using Type Inference and
Anonymous Types
lThe var keyword allows you to define a
local variable without explicitly specifying
the variable type
Dharmendra Bhatti 63
Using Type Inference and
Anonymous Types
l// Using Type Inference in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 64
Prof. (Dr.) Dharmendra Bhatti 32
2023 Lecture Notes of Web Technology
with .NET
Using Type Inference and
Anonymous Types
lIt is not that the names variable does not
have a type; instead, compiler infer the
type from the code.
Dharmendra Bhatti 65
Using Type Inference and
Anonymous Types
l// Creating an Anonymous Type in the
HomeController.cs File in the Controllers
Folder
Dharmendra Bhatti 66
Prof. (Dr.) Dharmendra Bhatti 33
2023 Lecture Notes of Web Technology
with .NET
Using Asynchronous Methods
lAsynchronous methods perform work in
the background and notify you when they
are complete, allowing your code to take
care of other business while the
background work is performed.
Dharmendra Bhatti 67
Using Asynchronous Methods
l// add a class file called
MyAsyncMethods.cs to the Models folder
Dharmendra Bhatti 68
Prof. (Dr.) Dharmendra Bhatti 34
2023 Lecture Notes of Web Technology
with .NET
Using Asynchronous Methods
l// Using the async and await Keywords in
the MyAsyncMethods.cs File
Dharmendra Bhatti 69
Using Asynchronous Methods
l// An Asynchronous Action Method in the
HomeController.cs File
Dharmendra Bhatti 70
Prof. (Dr.) Dharmendra Bhatti 35
2023 Lecture Notes of Web Technology
with .NET
HTTP
lHTTP is a stateless protocol
Dharmendra Bhatti 71
HTTP
lSecond (repeat) request from A to B
Dharmendra Bhatti 72
Prof. (Dr.) Dharmendra Bhatti 36
2023 Lecture Notes of Web Technology
with .NET
HTTP
Dharmendra Bhatti 73
HTTP
Dharmendra Bhatti 74
Prof. (Dr.) Dharmendra Bhatti 37
2023 Lecture Notes of Web Technology
with .NET
HTTP Response
Dharmendra Bhatti 75
Cookies
lDo we really need state management?
Dharmendra Bhatti 76
Prof. (Dr.) Dharmendra Bhatti 38
2023 Lecture Notes of Web Technology
with .NET
Cookies
lCookies are small pieces of data that websit
es store within web browsers and retrieve
later.
lCookies in ASP.NET Core are used to ident
ify specific users and manage session infor
mation.
Dharmendra Bhatti 77
Cookies
lTypes of Cookies
¡Session Cookies
¡Persistent Cookies
Dharmendra Bhatti 78
Prof. (Dr.) Dharmendra Bhatti 39
2023 Lecture Notes of Web Technology
with .NET
Cookies
lSession Cookies:
¡Session cookies are temporary cookies that are
stored on the user's computer for the duration
of their visit to a website.
¡They are typically used to maintain session stat
e and are destroyed when the user closes their
browser or navigates away from the web page.
Dharmendra Bhatti 79
Cookies
lPersistent cookies
¡Persistent cookies are long-
term cookies that can be stored across multiple
sessions.
¡They retain information such as login credential
s or user preferences, allowing users to
have a personalized experience when they revi
sit a website.
Dharmendra Bhatti 80
Prof. (Dr.) Dharmendra Bhatti 40
2023 Lecture Notes of Web Technology
with .NET
Cookies
lWriting a Cookie:
¡CookieOptions options = new CookieOptions();
¡options.Expires = DateTime.Now.AddDays(7);
¡Response.Cookies.Append("somekey",
"somevalue", options);
Dharmendra Bhatti 81
Cookies
lReading a Cookie:
lstring cookieValue =
Request.Cookies["Key"];
Dharmendra Bhatti 82
Prof. (Dr.) Dharmendra Bhatti 41
2023 Lecture Notes of Web Technology
with .NET
Cookies
lThe CookieOptions class provides
additional properties that can be set when
creating a cookie, including:
lDomain: Specifies the domain associated with the
cookie.
lExpiration time: Determines the cookie's expiration
time.
lPath: Defines the path for which the cookie is valid.
lSecurity policy: Specifies if the cookie should be
accessible only over HTTPS.
lHttpOnly: Indicates if the cookie is available only to
the server. Dharmendra Bhatti 83
Cookies
lDeleting a Cookie:
¡Response.Cookies.Delete("somekey");
Dharmendra Bhatti 84
Prof. (Dr.) Dharmendra Bhatti 42
2023 Lecture Notes of Web Technology
with .NET
Cookies
lProgram.cs
Dharmendra Bhatti 85
Cookies
lProgram.cs
Dharmendra Bhatti 86
Prof. (Dr.) Dharmendra Bhatti 43
2023 Lecture Notes of Web Technology
with .NET
Cookies
lProgram.cs
Dharmendra Bhatti 87
Cookies
lCookieOptions Properties
¡Domain: This property specifies the hosts to
which the browser will send the cookie. By
default, the cookie will be sent only to the host
that created the cookie.
¡Expires: This property sets the expiry for the
cookie.
¡HttpOnly: When true, this property tells the
browser not to include the cookie in requests
made by JavaScript code.
Dharmendra Bhatti 88
Prof. (Dr.) Dharmendra Bhatti 44
2023 Lecture Notes of Web Technology
with .NET
Cookies
lCookieOptions Properties
¡IsEssential: This property is used to indicate
that a cookie is essential, as described in the
“Managing Cookie Consent” section.
¡MaxAge: This property specifies the number of
seconds until the cookie expires. Older
browsers do not support cookies with this
setting.
¡Path: This property is used to set a URL path
that must be present in the request before the
cookie will be sent by the
Dharmendra browser.
Bhatti 89
Cookies
lCookieOptions Properties
¡SameSite: This property is used to specify
whether the cookie should be included in cross-
site requests. The values are Lax, Strict, and
None (which is the default value).
¡Secure: When true, this property tells the
browser to send the cookie using HTTPS only.
Dharmendra Bhatti 90
Prof. (Dr.) Dharmendra Bhatti 45
2023 Lecture Notes of Web Technology
with .NET
Cookies
lCookies are sent in the response header,
which means that cookies can be set only
before the response body is written, after
which any changes to the cookies are
ignored.
Dharmendra Bhatti 91
Cookies
lEnabling Cookie Consent Checking
lThe EU General Data Protection
Regulation (GDPR) requires the user’s
consent before nonessential cookies can
be used
Dharmendra Bhatti 92
Prof. (Dr.) Dharmendra Bhatti 46
2023 Lecture Notes of Web Technology
with .NET
Cookies
lEnabling Cookie Consent Checking
Dharmendra Bhatti 93
Cookies
Dharmendra Bhatti 94
Prof. (Dr.) Dharmendra Bhatti 47
2023 Lecture Notes of Web Technology
with .NET
Cookies
Dharmendra Bhatti 95
ConsentMiddleware.cs
Dharmendra Bhatti 96
Prof. (Dr.) Dharmendra Bhatti 48
2023 Lecture Notes of Web Technology
with .NET
Cookies – Example1
l public class CookiesController : Controller
{
public IActionResult Index()
{
if(!HttpContext.Request.Cookies.ContainsKey("first_request"))
{
HttpContext.Response.Cookies.Append("first_request", DateTime.Now.ToString());
return Content("Welcome, new visitor!");
}
else
{
DateTime firstRequest =
DateTime.Parse(HttpContext.Request.Cookies["first_request"]);
return Content("Welcome back, user! You first visited us on: " +
firstRequest.ToString());
}
}
}
Dharmendra Bhatti 97
Cookies – Example1
Dharmendra Bhatti 98
Prof. (Dr.) Dharmendra Bhatti 49
2023 Lecture Notes of Web Technology
with .NET
Cookies – Example2 -
HomeController.cs
Dharmendra Bhatti 99
Cookies – Example2 - Index.cshtml
Dharmendra Bhatti 100
Prof. (Dr.) Dharmendra Bhatti 50
2023 Lecture Notes of Web Technology
with .NET
Cookies – Example2 -
HomeController.cs
Dharmendra Bhatti 101
Cookies – Example3 -
HomeController.cs
Dharmendra Bhatti 102
Prof. (Dr.) Dharmendra Bhatti 51
2023 Lecture Notes of Web Technology
with .NET
Cookies – Example3 - Index.cshtml
Dharmendra Bhatti 103
Cookies – Example3 -
HomeController.cs
Dharmendra Bhatti 104
Prof. (Dr.) Dharmendra Bhatti 52
2023 Lecture Notes of Web Technology
with .NET
Cookies – Summary
lCookies store data across requests.
lBecause cookies are sent with every
request, their size should be kept to a
minimum.
lIdeally, only an identifier should be stored
in a cookie with the data stored by the
app.
lMany browsers restrict cookie size to 4096
bytes.
Dharmendra Bhatti 105
Cookies – Summary
lOnly a limited number of cookies are
available for each domain.
lBecause cookies are subject to tampering,
they must be validated by the app.
lCookies can be deleted by users and
expire on clients.
lCookies are often used for personalization
Dharmendra Bhatti 106
Prof. (Dr.) Dharmendra Bhatti 53
2023 Lecture Notes of Web Technology
with .NET
State Management
lCookies
lSession
lTempData
lQuery strings
lHidden fields
lCache
Dharmendra Bhatti 107
Sessions
lClient side Cookies Vs Server side
Sessions
Dharmendra Bhatti 108
Prof. (Dr.) Dharmendra Bhatti 54
2023 Lecture Notes of Web Technology
with .NET
Sessions
lSession state uses a store maintained by
the app to persist data across requests
from a client.
lCritical application data should be stored
in the user database and cached in
session only as a performance
optimization.
Dharmendra Bhatti 109
Sessions
lASP.NET Core maintains session state by
providing a cookie to the client that
contains a session ID.
lThe cookie session ID:
¡Is sent to the app with each request.
¡Is used by the app to fetch the session data.
Dharmendra Bhatti 110
Prof. (Dr.) Dharmendra Bhatti 55
2023 Lecture Notes of Web Technology
with .NET
Sessions
lThe session cookie is specific to the
browser. Sessions aren't shared across
browsers.
lSession cookies are deleted when the
browser session ends.
lIf a cookie is received for an expired
session, a new session is created that
uses the same session cookie.
Dharmendra Bhatti 111
Sessions
lEmpty sessions aren't retained. The
session must have at least one value set
to persist the session across requests.
When a session isn't retained, a new
session ID is generated for each new
request.
Dharmendra Bhatti 112
Prof. (Dr.) Dharmendra Bhatti 56
2023 Lecture Notes of Web Technology
with .NET
Sessions
lThe app retains a session for a limited
time after the last request. The app either
sets the session timeout or uses the
default value of 20 minutes. Session state
is ideal for storing user data:
¡That's specific to a particular session.
¡Where the data doesn't require permanent
storage across sessions.
Dharmendra Bhatti 113
Sessions
lSession data is deleted either when the
ISession.Clear implementation is called or
when the session expires.
lThere's no default mechanism to inform
app code that a client browser has been
closed or when the session cookie is
deleted or expired on the client.
Dharmendra Bhatti 114
Prof. (Dr.) Dharmendra Bhatti 57
2023 Lecture Notes of Web Technology
with .NET
Sessions
lSession state cookies aren't marked
essential by default. Session state isn't
functional unless tracking is permitted by
the site visitor.
lThere is no replacement for the cookieless
session feature from the ASP.NET
Framework because it's considered
insecure and can lead to session fixation
attacks.
Dharmendra Bhatti 115
Sessions
lThe in-memory cache provider stores
session data in the memory of the server
where the app resides.
lIn a server farm scenario:
¡Use sticky sessions to tie each session to a
specific app instance on an individual server.
Dharmendra Bhatti 116
Prof. (Dr.) Dharmendra Bhatti 58
2023 Lecture Notes of Web Technology
with .NET
Sessions
lSticky sessions can affect scalability and
complicate web app updates.
lA better approach is to use a Redis or
SQL Server distributed cache, which
doesn't require sticky sessions.
Dharmendra Bhatti 117
Sessions
lTo enable the session middleware,
Program.cs must contain:
¡Any of the IDistributedCache memory caches.
¡A call to AddSession
¡A call to UseSession
Dharmendra Bhatti 118
Prof. (Dr.) Dharmendra Bhatti 59
2023 Lecture Notes of Web Technology
with .NET
Sessions
Dharmendra Bhatti 119
The Session Storage Methods
lAddDistributedMemoryCache
¡This method sets up an in-memory cache.
¡Despite the name, the cache is not distributed
and is responsible only for storing data for the
instance of the ASP.NET Core runtime where it
is created.
Dharmendra Bhatti 120
Prof. (Dr.) Dharmendra Bhatti 60
2023 Lecture Notes of Web Technology
with .NET
The Session Storage Methods
lAddDistributedSqlServerCache
¡This method sets up a cache that stores data in
SQL Server and is available when the
Microsoft.Extensions.Caching.SqlServer
package is installed.
Dharmendra Bhatti 121
The Session Storage Methods
lAddStackExchangeRedisCache
¡This method sets up a Redis cache and is
available when the Microsoft.
Extensions.Caching.Redis package is installed.
Dharmendra Bhatti 122
Prof. (Dr.) Dharmendra Bhatti 61
2023 Lecture Notes of Web Technology
with .NET
Sessions
Dharmendra Bhatti 123
Using Session Data
Dharmendra Bhatti 124
Prof. (Dr.) Dharmendra Bhatti 62
2023 Lecture Notes of Web Technology
with .NET
Session – Example1 - Install NuGet
Package
lAdd Dependency using NuGet
Dharmendra Bhatti 125
Session – Example1 - Install NuGet
Package
lSearch for “Session”
Dharmendra Bhatti 126
Prof. (Dr.) Dharmendra Bhatti 63
2023 Lecture Notes of Web Technology
with .NET
Session – Example1 - Install NuGet
Package
lInstalled NuGet Packages
Dharmendra Bhatti 127
Session – Example1 - Program.cs
Dharmendra Bhatti 128
Prof. (Dr.) Dharmendra Bhatti 64
2023 Lecture Notes of Web Technology
with .NET
Session – Example1 - Program.cs
Dharmendra Bhatti 129
Session – Example1 -
HomeController.cs
Dharmendra Bhatti 130
Prof. (Dr.) Dharmendra Bhatti 65
2023 Lecture Notes of Web Technology
with .NET
Session – Example1 - Index.cshtml
Dharmendra Bhatti 131
Session – Example1 -
HomeController.cs
Dharmendra Bhatti 132
Prof. (Dr.) Dharmendra Bhatti 66
2023 Lecture Notes of Web Technology
with .NET
Session – Example1 - Privacy.cshtml
Dharmendra Bhatti 133
Session – Example2 - Install NuGet
Package
lAdd Dependency using NuGet
Dharmendra Bhatti 134
Prof. (Dr.) Dharmendra Bhatti 67
2023 Lecture Notes of Web Technology
with .NET
Session – Example2 - Install NuGet
Package
lSearch for “Session”
Dharmendra Bhatti 135
Session – Example2 - Install NuGet
Package
lInstalled NuGet Packages
Dharmendra Bhatti 136
Prof. (Dr.) Dharmendra Bhatti 68
2023 Lecture Notes of Web Technology
with .NET
Session – Example2 - Program.cs
Dharmendra Bhatti 137
Session – Example2 - Program.cs
Dharmendra Bhatti 138
Prof. (Dr.) Dharmendra Bhatti 69
2023 Lecture Notes of Web Technology
with .NET
Session – Example2 -
HomeController.cs
Dharmendra Bhatti 139
Session – Example2 - Index.cshtml
lInside the View,
the IHttpContextAccessor Interface object
is injected in order to access the Session
and its functions inside the View.
lAlso, the Service required in Program.cs
¡builder.Services.AddSingleton<IHttpContextAcc
essor, HttpContextAccessor>();
Dharmendra Bhatti 140
Prof. (Dr.) Dharmendra Bhatti 70
2023 Lecture Notes of Web Technology
with .NET
Session – Example2 - Index.cshtml
lAddSingleton is used for instances that
can be shared across the application.
lWith Singleton service, there is only a
single instance.
lAn instance is created, when service is
first requested and that single instance will
be used by all subsequent HTTP request
throughout the application.
Dharmendra Bhatti 141
Session – Example2 - Index.cshtml
Dharmendra Bhatti 142
Prof. (Dr.) Dharmendra Bhatti 71
2023 Lecture Notes of Web Technology
with .NET
Session – Example2 -
HomeController.cs
Dharmendra Bhatti 143
Session – Example2 - Privacy.cshtml
Dharmendra Bhatti 144
Prof. (Dr.) Dharmendra Bhatti 72
2023 Lecture Notes of Web Technology
with .NET
Example – Form1
lAdd FormModel.cs in Models folder
Dharmendra Bhatti 145
Example – Form1
lHomeController.cs
Dharmendra Bhatti 146
Prof. (Dr.) Dharmendra Bhatti 73
2023 Lecture Notes of Web Technology
with .NET
Example – Form1
lIndex.cshtml
Dharmendra Bhatti 147
Hidden Field
lThe <input type="hidden"> defines a
hidden input field.
lA hidden field lets web developers include
data that cannot be seen or modified by
users when a form is submitted.
lScope is destination page only.
Dharmendra Bhatti 148
Prof. (Dr.) Dharmendra Bhatti 74
2023 Lecture Notes of Web Technology
with .NET
Example – HiddenExample1
lAdd StudentModel.cs in Models folder
Dharmendra Bhatti 149
Example – HiddenExample1
lHomeController.cs
Dharmendra Bhatti 150
Prof. (Dr.) Dharmendra Bhatti 75
2023 Lecture Notes of Web Technology
with .NET
Example – HiddenExample1
lIndex.cshtml
Dharmendra Bhatti 151
Example – HiddenExample1
lPrivacy.cshtml
Dharmendra Bhatti 152
Prof. (Dr.) Dharmendra Bhatti 76
2023 Lecture Notes of Web Technology
with .NET
Working with HTTPS Connections
lSecure Socket Layer
lTransport Layer Security
lHTTP + TLS = HTTPS
Dharmendra Bhatti 153
Working with HTTPS Connections
lAdvantages:
lEncryption
lSite Verification
lCustomer Trust (Green Lock)
lSEO
Dharmendra Bhatti 154
Prof. (Dr.) Dharmendra Bhatti 77
2023 Lecture Notes of Web Technology
with .NET
Working with HTTPS Connections
lLimitations:
lCost
lPerformance
lCaching
Dharmendra Bhatti 155
Working with HTTPS Connections
Dharmendra Bhatti 156
Prof. (Dr.) Dharmendra Bhatti 78
2023 Lecture Notes of Web Technology
with .NET
Enabling HTTPS Connections
lHTTPS is enabled and configured in the
launchSettings.json file in the Properties
folder
Dharmendra Bhatti 157
Enabling HTTPS Connections
lHTTPS is enabled and configured in the
launchSettings.json file in the Properties
folder
Dharmendra Bhatti 158
Prof. (Dr.) Dharmendra Bhatti 79
2023 Lecture Notes of Web Technology
with .NET
Detecting HTTPS Requests
lHttpContext.Request.IsHttps
Dharmendra Bhatti 159
HttpsExample1 - Program.cs
lbuilder.Services.AddSingleton<IHttpConte
xtAccessor, HttpContextAccessor>();
l…
l//app.UseHttpsRedirection();
lapp.UseStaticFiles();
Dharmendra Bhatti 160
Prof. (Dr.) Dharmendra Bhatti 80
2023 Lecture Notes of Web Technology
with .NET
HttpsExample1 -
Properties/launchSettings.json
Dharmendra Bhatti 161
HttpsExample1 - Index.cshtml
Dharmendra Bhatti 162
Prof. (Dr.) Dharmendra Bhatti 81
2023 Lecture Notes of Web Technology
with .NET
Enforcing HTTPS Requests
lEnforcing HTTPS in the Program.cs
lapp.UseHttpsRedirection();
Dharmendra Bhatti 163
Configuring Https Redirection
l...
lbuilder.Services.AddHttpsRedirection(opts
=> {
¡opts.RedirectStatusCode =
StatusCodes.Status307TemporaryRedirect;
¡opts.HttpsPort = 443;
l});
l...
Dharmendra Bhatti 164
Prof. (Dr.) Dharmendra Bhatti 82
2023 Lecture Notes of Web Technology
with .NET
HTTP Strict Transport Security
lOne limitation of HTTPS redirection is that
the user can make an initial request using
HTTP before being redirected to a secure
connection, presenting a security risk.
lPossible Attacks:
¡protocol downgrade
¡cookie hijacking attacks
Dharmendra Bhatti 165
Dharmendra Bhatti 166
Prof. (Dr.) Dharmendra Bhatti 83
2023 Lecture Notes of Web Technology
with .NET
User requests page over HTTPS
Dharmendra Bhatti 167
Enabling HTTP Strict Transport
Security
lHSTS works by including a header in
responses that tells browsers to use
HTTPS only when sending requests to the
web application’s host.
lAfter an HSTS header has been received,
browsers that support HSTS will send
requests to the application using HTTPS
even if the user specifies an HTTP URL.
Dharmendra Bhatti 168
Prof. (Dr.) Dharmendra Bhatti 84
2023 Lecture Notes of Web Technology
with .NET
HTTP Strict Transport Security
Dharmendra Bhatti 169
Enabling HTTP Strict Transport
Security
Dharmendra Bhatti 170
Prof. (Dr.) Dharmendra Bhatti 85
2023 Lecture Notes of Web Technology
with .NET
The HSTS Configuration Properties
Dharmendra Bhatti 171
Enabling HTTP Strict Transport
Security
lInitially low HSTS like 1 day
lDefault HSTS is 30 days
lSet HSTS value to 1 year if client no
longer require http
Dharmendra Bhatti 172
Prof. (Dr.) Dharmendra Bhatti 86
2023 Lecture Notes of Web Technology
with .NET
Enabling HTTP Strict Transport
Security
lHSTS is disabled during development and
enabled only in production, which is why
the UseHsts method is called only for that
environment.
Dharmendra Bhatti 173
Configuration for common web
servers
lOn Apache, you would apply
a Header directive to always set the HSTS
header in .htaccess file
l<VirtualHost www.example.com:80>
¡Header always set Strict-Transport-Security
"max-age=63072000; includeSubdomains;
preload"
l</VirtualHost>
Dharmendra Bhatti 174
Prof. (Dr.) Dharmendra Bhatti 87
2023 Lecture Notes of Web Technology
with .NET
Configuration for common web
servers
lFor IIS 7.0 and up
Dharmendra Bhatti 175
Handling Exceptions and Errors
lWhen the request pipeline is created, the
WebApplicationBuilder class uses the
development environment to enable
middleware that handles exceptions by
producing HTTP responses that are
helpful to developers.
Dharmendra Bhatti 176
Prof. (Dr.) Dharmendra Bhatti 88
2023 Lecture Notes of Web Technology
with .NET
ExceptionExample1 - Program.cs
l…
l app.Run(context => {
l throw new Exception("Something went
wrong!");
l });
l app.Run();
Dharmendra Bhatti 177
ExceptionExample1
Dharmendra Bhatti 178
Prof. (Dr.) Dharmendra Bhatti 89
2023 Lecture Notes of Web Technology
with .NET
ExceptionExample1 -
Properties/launchSettings.json
lIn Properties/launchSettings.json file,
change
¡"ASPNETCORE_ENVIRONMENT": "Development”
¡to
¡"ASPNETCORE_ENVIRONMENT": ”Production"
Dharmendra Bhatti 179
ExceptionExample1
Dharmendra Bhatti 180
Prof. (Dr.) Dharmendra Bhatti 90
2023 Lecture Notes of Web Technology
with .NET
Returning an HTML Error Response
lIn Program.cs file,
lif (!app.Environment.IsDevelopment())
l{
l app.UseExceptionHandler("/error.html");
l app.UseHsts();
l}
Dharmendra Bhatti 181
Returning an HTML Error Response
lIn wwwroot folder, create an html file
“error.html”
Dharmendra Bhatti 182
Prof. (Dr.) Dharmendra Bhatti 91
2023 Lecture Notes of Web Technology
with .NET
ExceptionExample1 -
Properties/launchSettings.json
lIn Properties/launchSettings.json file,
change
¡"ASPNETCORE_ENVIRONMENT": "Development”
¡to
¡"ASPNETCORE_ENVIRONMENT": ”Production"
Dharmendra Bhatti 183
Returning an HTML Error Response
Dharmendra Bhatti 184
Prof. (Dr.) Dharmendra Bhatti 92
2023 Lecture Notes of Web Technology
with .NET
Enriching Status Code Responses
lIn project directory, add a new empty class
file Responses.cs
Dharmendra Bhatti 185
Enriching Status Code Responses
Dharmendra Bhatti 186
Prof. (Dr.) Dharmendra Bhatti 93
2023 Lecture Notes of Web Technology
with .NET
Enriching Status Code Responses
lAdding Status Code Middleware in the
Program.cs File
Dharmendra Bhatti 187
Enriching Status Code Responses
lhttps://localhost:7124/error
Dharmendra Bhatti 188
Prof. (Dr.) Dharmendra Bhatti 94
2023 Lecture Notes of Web Technology
with .NET
Filtering Requests Using the Host
Header
lThe default configuration for the Hosts
header middleware is included in the
appsettings.json file
Dharmendra Bhatti 189
The HostFilteringOptions Properties
Dharmendra Bhatti 190
Prof. (Dr.) Dharmendra Bhatti 95
2023 Lecture Notes of Web Technology
with .NET
Filtering Requests Using the Host
Header
lConfiguring Host Header Filtering in the
Program.cs File
Dharmendra Bhatti 191
Filtering Requests Using the Host
Header
Dharmendra Bhatti 192
Prof. (Dr.) Dharmendra Bhatti 96
2023 Lecture Notes of Web Technology
with .NET
Questions ???
Dharmendra Bhatti 193
Prof. (Dr.) Dharmendra Bhatti 97