Unit-1 Net Core Framework
Unit-1 Net Core Framework
INSTITUTE OF SCIENCE & TECHNOLOGY FOR ADVANCED STUDIES & RESEARCH (ISTAR)
M.Sc. (Information Technology)
Semester – II
Prepared By:
Dr. Suchita Patel
Assistant Professor
M.Sc. (IT) Department, ISTAR
Unit 2: Controllers & Action Methods: Controllers Overview; Action Methods and
IActionResult object; Passing data from Controller to View; Understanding Action
Selectors; Action Filters; Building Custom Action Filters; Middleware;
Asynchronous Action Methods
ASP.NET Core MVC – Basic
ASP.NET Core MVC – Data Passing Techniques
ASP.NET Core MVC – Routing
ASP.NET Core MVC – Action Results
Unit 3: Views & Helpers: Introducing Razor View; Advantages of Razor View;
Razor Syntax; Types of Views; Partial Views; Layout Pages; Special Views; View
Categorization based on Model ; Html Helpers; Built-In Html Helpers; URL
helpers; Tag Helpers; Custom Tag Helpers
ASP.NET Core MVC – Views
ASP.NET Core MVC – HTML Helpers
ASP.NET Core MVC – Tag Helpers
Reference Books:
1 Programming ASP.NET Core, by Dino Esposito
2 Learn ASP. NET Core 3: Develop Modern Web Applications with ASP. NET Core 3, Visual
Studio 2019, and Azure, 2nd Edition, by Kenneth Yamikani Fukizi, Jason De Oliveira, Michel
Bruchet
3 ASP.NET Core Application Development: Building an application in four sprints By James
Chambers, David Paquette, Simon Timms
4 Learning ASP.NET Core MVC Programming by Mugilan T. S. Ragupathi
Unit 1: ASP.NET Core: Introduction to ASP.NET Core; What is ASP.NET Core? ;
ASP.NET Core Features ; Advantages of ASP.NET Core ; MVC Pattern ;
Understanding ASP.NET Core MVC ; ASP.NET Core vs. ASP.NET MVC vs. ASP.NET
Web Forms; ASP.NET Core Environment Setup; ASP .NET Core First Application;
Project Layout; Understanding Life Cycle of ASP.Net Core Request
Prerequisites
Basic knowledge of .NET Framework 4.5, C#, and Visual Studio is required.
Let us look at the different web technologies Microsoft has provided to develop
web applications and web services. Microsoft offers several frameworks for
developing web applications and web services through ASP.NET. These
frameworks include ASP.NET Web Forms, ASP.NET MVC, ASP.NET Web
API, ASP.NET Core, Razoe Pages, Blazor, and more. Each serves a distinct
purpose, and none of the frameworks are meant to replace the others. Let us
have an overview of all these Microsoft Web Technologies:
ASP.NET MVC:
ASP.NET MVC (Model-View-Controller) is a framework that was introduced
by Microsoft in 2009 as part of the .NET Framework 3.5. It provides an
alternative to Web Forms, offering a framework that emphasizes a clear
separation of concerns and full control over the generated HTML markup. It
follows the Model-View-Controller (MVC) architectural pattern, which allows
developers to build scalable, testable, and maintainable web applications.
Current Status: While ASP.NET MVC is still supported, Microsoft has shifted its
focus to ASP.NET Core MVC, which offers cross-platform capabilities and
enhanced performance. For new projects, ASP.NET Core MVC is recommended.
New Projects: Prefer NET Core MVC or Razor Pages for traditional web
applications, and Blazor for interactive client-side applications.
API Development: Use .NET Core Web API to build robust, scalable
APIs.
Legacy Maintenance: Continue maintaining existing ASP.NET Web
Forms, ASP.NET MVC, and ASP.NET Web API applications, but consider
planning migrations to modern ASP.NET Core frameworks.
Cross-Platform Needs: Use NET Core frameworks to develop and
deploy applications on multiple operating systems.
Full-Stack .NET Development: Use Blazor to streamline development
using C# across both client and server sides.
Introduction to ASP.NET Core Framework
ASP.NET Core is a Cross-Platform, Open-Source, High-Performance framework
used for building modern, cloud-based, and internet-connected applications that
run on Windows, Linux, macOS, and Docker. According to Microsoft:
ASP.NET Core is the modern, high-performance web development
framework for .NET, that runs on Windows, Linux, macOS, and Docker.
ASP.NET is a popular web development framework for building web apps
on the .NET platform.
ASP.NET Core is the open-source version of ASP.NET that runs on macOS,
Linux, and Windows. It was first released in 2016 and is a redesign of
earlier Windows-only versions of ASP.NET.
ASP.NET Core is a cross-platform framework used for building web apps and
backend API services. It is based on the MVC (Model View Controller) Software
Pattern.
High Performance:
ASP.NET Core is optimized for high performance. Its modular architecture allows
developers to include only necessary dependencies, resulting in faster and more
efficient applications. Benchmarks demonstrate that applications developed with
ASP.NET Core are significantly faster than those built with previous versions of
ASP.NET and are ideal for high-traffic, cloud-native applications. For a better
understanding, please look at the following image, which is provided on the
Official Microsoft Site:
Open Source
ASP.NET Core framework is open-source, which is the main reason for its
popularity. The entire source code for ASP.NET Core Framework is available on
GitHub at https://github.com/dotnet/aspnetcore, and allows developers to:
Download and inspect the source code.
Modify and customize it as needed.
Contribute to its development, benefiting from a huge community with
over 100,000 contributions from more than 3,700 companies.
All aspects of .NET are open source, including class libraries, runtime, compilers,
languages, the ASP.NET Core web framework, Windows desktop frameworks, the
Entity Framework Core data access library, and more.
The ASP.NET Core team is always there to support your effort in developing the
application. It receives bug fixing and improvement updates on a regular basis,
usually within a short time period. You don’t have to wait longer for updates. For
more information, visit the official ASP.NET Core
page: https://dotnet.microsoft.com/en-us/platform/open-source
Cross-Platform:
The ASP.NET Core Framework is designed from scratch to be Cross-Platform,
meaning ASP.NET apps can be developed and run on Windows, Linux, macOS,
and Docker. This means we can build applications that run across different
operating systems without needing to build different applications for different
platforms using different frameworks.
Cloud-Ready:
ASP.NET Core is designed for cloud deployment. It provides configuration
features that simplify deploying and scaling applications in cloud environments
like Microsoft Azure.
ASP.NET Core Support Policy and Release Lifecycle:
The latest stable version of .NET Core is .NET 8, released in November 2023.
Starting with .NET 5, the term “Core” was removed, and it is now simply called
.NET (e.g., .NET 6, .NET 7, .NET 8). Microsoft releases new major versions every
year in November, alternating between Long-Term Support (LTS) and Short-
Term Support (STS) releases:
Long-Term Support (LTS) Releases: Even-numbered releases (e.g., .NET
6, .NET 8) are designated as LTS releases. They receive support and patches
for three years, making them ideal for production environments.
Standard-Term Support (STS) Releases: Odd-numbered releases (e.g.,
.NET 5, .NET 7) receive support and patches for 18 months, suitable for
projects that can adopt newer versions more frequently.
For a better understanding, please have a look at the following image:
Note: Customers can choose Long Term Support (LTS) releases or Standard
Term Support (STS) releases. The quality of all releases is the same. The only
difference is the length of support. LTS releases get free support and patches for 3
years. STS releases get free support and patches for 18 months.
ASP.NET Core is a web framework for building web applications, services, and
APIs. .NET Core is the runtime that supports running ASP.NET Core applications.
It is also the foundation for other types of applications like console, desktop, and
mobile apps (through .NET MAUI). So, .NET Core provides the runtime
environment, while ASP.NET Core is the web application framework that runs on
it.
For a better understanding, please have a look at the following diagram:
ASP.NET Core:
ASP.NET Core is an Open-Source, Cross-Platform Framework using which
we can develop different types of Web Applications, such as MVC, Web API,
Razor Pages, etc.
If you want to develop and run .NET Core Applications, you need to install
the .NET Core SDK, which will automatically install the .NET Runtime. If you
only want to run .NET Core Applications, you only need to install the .NET
Core Runtime.
ASP.NET Core 8 is the latest stable version.
ASP.NET Core Environment Setup
Operating System:
ASP.NET Core development can be done on any modern operating system, such
as Windows, macOS, or Linux. I will use the Windows Operating System in this
Course.
Windows 10/11: It is Ideal for .NET development, as it fully supports
Visual Studio and .NET 8. It also allows easy integration with Microsoft SQL
Server.
macOS or Linux: These can also be used for .NET development, but keep in
mind that some Microsoft-specific tools like SQL Server Management
Studio are not available natively on these platforms.
.NET SDK:
This is the software development kit for developing and running applications
with ASP.NET Core. It includes the .NET runtime, libraries, and command-line
tools.
ASP.NET Core:
ASP.NET Core is the framework for building web applications, including Web
APIs, with .NET Core. It is included in the .NET SDK and can be installed using the
command line or through the Visual Studio installer. When we install the .NET 8
SDK, it includes the latest ASP.NET Core libraries necessary for Web
development.
API Client:
Postman/Fiddler: This is a versatile API client that works on Windows,
macOS, and Linux. It’s useful for testing and documenting APIs developed
with ASP.NET Core.
Swagger (OpenAPI): Integrating Swagger into your ASP.NET Core project
allows you to generate interactive API documentation and UI automatically,
which can be accessed through your web application.
These are the essential software components required for ASP.NET Core MVC
and Web API development.
How to Download and Install Visual Studio 2022
Currently, .NET 8 has Long Term Support (LTS). Visual Studio 2022 supports
.NET 8. You can use your favorite IDE, such as Visual Studio 2022, Visual Studio
Code, Sublime Text, etc., to develop, build, and run .NET Core Applications. I
installed the Windows Operating System on my machine. So, I will use Visual
Studio 2022 as my editor, or you can say Integrated Development Environment
(IDE) for developing ASP.NET Core Applications. But this is not mandatory. You
can use any editor of your choice.
If you are a student or want to learn .NET, you can select the Community Edition,
which is absolutely free.
You can also double-click the EXE file downloaded on your machine, as shown in
the image below.
Once you double-click, a popup will appear asking if you want to allow this app to
change your device. Click the Yes button to continue.
If you already have Visual Studio 2022 installed, ensure that ASP.NET and Web
Development are installed. If not installed, you can install them using Visual
Studio Installer. Make sure .NET 8.0 Runtime and .NET SDK are checked under
the Individual Components section, as shown below.
Once you install it, you can verify it using the command prompt (Windows OS)
and Terminal (Linus OS). On my Machine, I have installed the Windows Operating
System. So, I can verify it using the “dotnet –list-sdks” command, as shown in the
image below. This command will give you a list of all SDKs installed on your
machine.
If the .NET 8 Framework is installed successfully on your machine, they will see
the version number shown in the above image.
If you are using the Windows Operating System, please visit the website below.
https://dotnet.microsoft.com/download
You will find the following webpage once you go to the above website. The latest
version at this point is .NET 8, which provides Long-Term Support, as shown in
the image below. In this course, we are going to use .NET 8.
As we are here to develop, build, run, and deploy .NET Core Applications, we need
to click the Download .NET SDK x64 link. Once you click on the Download .NET
SDK x64 button, it will download the .NET SDK and navigate to the page below,
which shows how to Run the Installer, Verify the Installation, and get started, as
shown in the below page.
Note: If you installed .NET SDK on your machine, you do not need to install .NET
Runtime separately, as .NET SDK automatically installs the .NET Runtime.
Another point you need to remember is that once you install .NET SDK, ASP.NET
Core is automatically installed.
It displays the OS name, version, platform, etc. Further, it also installed .NET
Runtimes. Please make sure .NET 8 is installed on your machine, as we are going
to develop the applications using .NET 8.
If you want to see what is the latest version installed on your machine, please use
the dotnet –version command as shown in the image below:
Note: The .NET SDK provides a complete environment for developing, building,
testing, and deploying ASP.NET Core Web API Applications.
Introduction to ASP.NET Core MVC Framework
MVC is a Design Pattern, and ASP.NET Core MVC is a framework based on the
MVC Design Pattern.
What is MVC?
MVC stands for Model View and Controller. It is an Architectural Design Pattern,
which means it is used at the application’s architecture level. So, MVC is not a
programming language, not a Framework. It is a Design Pattern. When we design
an application, we first create its architecture, and MVC plays an important role
in designing that architecture.
Once the controller creates the model, it selects a view to render the domain or
model data. While selecting a view, it is also the controller’s responsibility to pass
the model data. In the MVC design pattern, the view’s only responsibility is
rendering the model data. So, in MVC, the view is the component responsible for
generating the necessary HTML to render the model data. Once the view
generates the HTML, that HTML is sent to the client over the network who
initially made the request.
The three major components of an ASP.NET Core MVC Application are the Model,
View, and Controller.
So, in short, we can say that a Model in the MVC Design Pattern contains a set of
classes used to represent the data and the logic to manage those data. In our
example, the Student class represents the data. The StudentBusinessLayer class
manages the student data, validates it, and stores it in the database.
For example, we want to display Student data on a web page. The student model
carried the student data to the view. As already discussed, the view’s one and
only responsibility is to render the model data, in this case, student model data.
The following code does the same thing.
https://localhost:7132/Student/Details/2
Then, that request is mapped to the Details action method of the Student
Controller using the Routing defined for our application. We will discuss Routing
in detail in our coming articles. For now, look at the following Controller code:
As you can see in the example, the Student Controller creates the Student object
within the Details action method. So, here, the Student is the Model. The
controller uses the StudentBusinessLayer class to fetch the Student data from the
database.
Once the controller creates the Student model with the necessary student data, it
passes the Student model to the Details view. The Details view then generates the
necessary HTML to present the Student data. Once the HTML is generated, it is
sent to the client over the network who initially made the request.
Note: The Controller and View depend on the Model in the MVC Design Pattern,
but the Model never depends on either View or Controller. This is one of the main
reasons for the separation of concerns, which allows us to build and test the
model independently of the visual presentation.
What is ASP.NET Core MVC?
ASP.NET Core MVC is a web application development framework developed by
Microsoft. It is a modern implementation of the Model-View-Controller (MVC)
architectural pattern designed to build dynamic web applications and web APIs.
It is part of the ASP.NET Core platform, a cross-platform, high-performance
framework for building modern, cloud-based, and internet-connected
applications. So, the point that you need to remember is that MVC is a Design
Pattern, and ASP.NET Core MVC is a Framework based on the MVC Design
Pattern.
Support for Web APIs: ASP.NET Core MVC can be used to develop RESTful
HTTP services. It fully supports formatting response data as JSON or XML
and can easily handle different content types with content negotiation.
Once you click on the Create a new project box, the “Create a new project”
window will open. This window includes different .NET 8 application templates.
Here, we will create a simple Web application from scratch, so select the ASP.NET
Core Empty project template and click the Next button, as shown in the image
below.
What is an ASP.NET Core Empty Project Template?
The ASP.NET Core Empty template selection indicates that we are creating an
empty ASP.NET Core project. This template comes with a minimal setup, i.e., with
the basic structure for an ASP.NET Core project, without pre-configured
controllers, views, or APIs.
Once you click on the Next button, it will open the following Configure Your
New Project window. Here, you need to provide the necessary information to
create a new project. First, give an appropriate name for your project
(FirstCoreWebApplication), set the location where you want to create this
project, and the solution name for the ASP.NET Core Web application. And finally,
click on the Create button, as shown in the image below.
Project name:
This is the field where we need to specify the name of our new project. Here, we
specified the project name as FirstCoreWebApplication. The project name will
also be used as the default namespace in our code files. It should be descriptive
and unique to easily identify the project within our solution.
Location:
The location text box specifies the directory where the project will be created on
our local system. In this case, the project location is set to “D:\Projects”. You can
choose a different folder by either typing the path or clicking the … button to
browse to a directory of your choice.
Solution name:
A solution is a container for one or more projects, and the solution name usually
matches the project name when you’re working on a single project. Visual Studio
organizes multiple related projects under a solution for ease of management. By
default, the solution name is the same as the project name, but you can modify it
if your solution contains multiple projects. Here, the Solution name field contains
“FirstCoreWebApplication”.
The first folder, FirstCoreWebApplication, is the solution folder, and the second
FirstCoreWebApplication is the project folder inside the solution folder.
In the above window, clicking on the Next button will open the Additional
Information window. Here, you need to select .NET 8 as the Framework, check
the Configure for HTTPS, Do not use top-level statements check boxes, and finally,
click the Create button, as shown in the image below.
Understanding the Additional Configuration Window:
Framework
This dropdown allows us to select the version of .NET you want to target. Here,
we need to select .NET 8.0 (Long-Term Support). This means we are building the
project using .NET 8.0, the latest version of the .NET platform, with long-term
support (LTS). LTS releases are maintained for a longer period, typically three
years, making them suitable for production applications.
Container OS
This dropdown becomes available if “Enable container support” is checked. It lets
us choose the operating system the container will use, either Linux or Windows.
As you can see by default, Linux is selected as the Container OS, but it is disabled
since Enable container support is unchecked, which is a common choice for
containers because of its lightweight nature.
So, once you click on the Create button, a new ASP.NET Core Web Application will
be created in Visual Studio 2022 using .NET 8. The project will have the following
file and folder structure.
Dependencies:
This folder manages all the NuGet packages, SDKs, .NET libraries, and any third-
party libraries that our project depends on. That means it includes both built-in
ASP.NET Core libraries and third-party libraries you might add later to enhance
your application’s functionality. By default, the basic ASP.NET Core dependencies,
such as Microsoft.NETCore.App and Microsoft.AspNetCore.App, will be included.
Microsoft.NETCore.App
This metapackage provides the essential runtime components and libraries
needed for any .NET Core application to run. When creating any type of .NET Core
application (such as console apps, Windows services, etc.), we will use the
libraries included in this package. This package provides the following features:
.NET Core Runtime: Includes the runtime libraries required to execute .NET
applications.
Core Libraries: Provides fundamental libraries such as System.Collections,
System.IO, System.Linq, System.Threading, and more. These libraries are
the foundation for all .NET Core applications.
Base Class Libraries (BCL): The BCL provides a standard set of classes that
include primitive data types, collections, file I/O, and other basic
functionalities required to build applications.
Microsoft.AspNetCore.App
This metapackage is specific to ASP.NET Core applications, providing the
necessary libraries and tools to create web applications, RESTful APIs, and
server-side services. When we create an ASP.NET Core application (web apps,
APIs, etc.), we will use this metapackage. This package provides the following
features:
NET Core Framework: It includes all the core libraries required to build
web applications, such as MVC, Razor Pages, API controllers, etc.
Entity Framework Core: Provides the default Object Relational Mapping
(ORM) library, which allows you to interact with databases.
Middleware Components: It contains built-in middleware components,
like routing, authentication, authorization, static file handling, logging, and
more, which are essential for ASP.NET Core web applications.
Dependency Injection and Configuration: Provides support for
configuring services and dependency injection, which are core concepts in
ASP.NET Core applications.
Identity: Includes components for implementing authentication, such as
ASP.NET Core Identity for managing users, roles, and sign-ins. So,
Microsoft.NETCore.App provides the core functionality needed to run any
.NET Core application. Microsoft.AspNetCore.App extends
Microsoft.NETCore.App and add ASP.NET Core-specific libraries and
functionality that are essential for building and running web applications.
What Are Analyzers?
Analyzers are tools integrated into Visual Studio that analyze your source code
while you are writing it. They help ensure code quality, identify potential
problems, enforce coding standards, identify bugs, and provide improvement
suggestions. They run in the background while you code and generate warnings
or errors in the editor if they find something that doesn’t conform to certain
coding standards or best practices.
Properties:
This folder contains the launchSettings.json file, configuring how our application
starts during development. It defines the environment, URLs, and profiles (IIS
Express, Kestrel, etc.) used to run the project locally using Visual Studio.
appsettings.json:
This is a configuration file where we can define key-value pairs for settings used
throughout our application. It typically includes connection strings, logging
configurations, API keys, or any other application-level configuration. It follows a
JSON structure and provides a centralized location for managing configurations
that can be easily accessed throughout the project.
Program.cs
This is the entry point of our ASP.NET Core application. The Program.cs file
contains the Main method, which is where our application starts. It also creates
the host for the application. This file configures the web server (Kestrel or IIS)
and the necessary middleware components that handle requests.
Here, the output “Hello World!” comes from the Main method of
the Program class, which is present inside the Program.cs file, as shown in the
below image.
Now, open the Program.cs class file and change the “Hello World!” string to
something else, as shown in the code below. Rerun the application, and the
output will change accordingly.
Summary of Responsibilities:
1. Root Directory
The root of the project contains key files for configuration and application entry
points:
Program.cs
o The main entry point of the application.
o It configures the web application, services, and middleware.
appsettings.json
o Stores application-wide settings such as database connection strings,
logging, and custom configurations.
appsettings.Development.json
o Environment-specific configuration file for the development
environment.
Properties/launchSettings.json
o Defines environment settings for debugging and launching the
application.
Example Product.cs:
Stores Razor view files (.cshtml) that generate the HTML output for the
user interface.
Organized into subfolders named after their corresponding controllers.
Key View Files:
If you use C# as the programming language, it will create the project file with the
“.csproj” extension. Similarly, if you use VB as the programming language, it will
create the project file with the “.vbproj” extension. However, with ASP.NET Core
(.NET), the project file’s format and content have changed significantly.
Let us understand what changes are made to the ASP.NET Core Project file with
an example.
<Project Sdk=”Microsoft.NET.Sdk.Web”>
This line specifies the SDK that the project will use. In this case, it is using
“Microsoft.NET.Sdk.Web”, which means it is an ASP.NET Core project with web-
specific configurations and dependencies. The Microsoft.NET.Sdk.Web SDK
provides the tools, libraries, and dependencies required to develop, build, and
run ASP.NET Core Web applications.
<PropertyGroup>
This section defines various project properties. Each property in this group
affects how the project is built or configured. Multiple PropertyGroup elements
can exist in a .csproj file. Properties within this group define aspects like the
target framework, nullable reference type handling, and implicit using.
<TargetFramework>net8.0</TargetFramework>:
This line defines the target framework that the project is built against.
TargetFramework specifies which version of the .NET runtime your application
will use. In this case, it is .NET 8.0. Targeting a specific framework version allows
the project to use features, libraries, and runtime optimizations specific to that
version of .NET.
<Nullable>enable</Nullable>:
This line enables nullable reference types for the project. This feature was
introduced in C# 8.0 and helps prevent null reference exceptions by making
reference types (like a string, class, etc.) either explicitly nullable or non-
nullable. When Nullable is set to enable:
The compiler will give warnings if a potentially null value is not handled
properly.
It makes code safer and more resilient to null-related runtime errors by
clearly distinguishing which variables are allowed to be null.
<ImplicitUsings>enable</ImplicitUsings>
Whenever we add new packages to our application, the package reference will
also be added to the application project file. Please have a look at the following
Dependencies section of our project. Whenever we add a package, that package
and its dependency packages will be stored here.
Let’s first add a package from the NuGet Package Manager and see what happens.
To do so, go to Tools => NuGet Package Manager => Manage NuGet Packages
for Solution… option from the context menu, as shown in the image below.
Now, let us add the Newtonsoft.json package. Select the browse tab, search for
Newtonsoft, and install it, as shown in the image below.
Once the package is installed successfully, a reference will be added inside the
dependencies section, as shown in the image below.
As we have only added one package, Newtonsoft.json, it added its package
references here. At the same time, it will also add that package reference in the
application project file, as shown in the image below.
Understanding <ItemGroup>
The <ItemGroup> element is used to define a group of items, such as package
references, project references, or folder references, that should be included in the
project. This specific ItemGroup contains one package reference:
Note: Once we delete that package, then it will delete the reference from both the
Package Dependencies as well as from the project file.
Deleting Package in ASP.NET Core:
Again, go to the NuGet Package Manager, select the installed tab, select the
package, and uninstall it, as shown in the image below.
Once you delete the package, it should remove the reference from both the
dependencies and the project file.
ASP.NET Core Main Method
Understanding Program.cs Class File in ASP.NET Core
When you open the Program.cs class file in an ASP.NET Core project, you will see
a few lines of code. These few lines handle all the setup needed to create a web
server, configure services, and start the application to listen for HTTP requests.
If you uncheck the “Do not use top-level statements” checkbox during project
creation, you won’t see the class or Main method name. This feature, introduced
in C# 9, allows you to write one “top-level” statement, meaning you don’t have to
explicitly define the Program class or the Main method. The file itself acts as the
application’s entry point.
Note: In earlier versions (before .NET 6), ASP.NET Core used two separate files:
Program.cs and Startup.cs.
The Program.cs file configured the host, and Startup.cs handled the services and
middleware.
Starting with .NET 6, these are merged into a single Program.cs file for simplicity.
Program Class:
This is the main class of every .NET application that serves as the entry point.
Main Method:
The Main method is the first method executed when an application runs. It’s a
static method, which means it runs without needing to create an object of the
Program class. When starting the application, it takes a string array (string[]
args) as a parameter to accept any command-line arguments.
The main method is responsible for doing four things. They are as follows:
This is the first line of code in the Main method used to create an instance of the
WebApplicationBuilder sealed class. The args parameter allows the application to
process any command-line arguments passed at application startup.
Note: As we progress in this course, we will see how we can configure different
types of built-in services like MVC, Web API, Razor Page, etc. as well as we will
also discuss how to create and configure Custom Services using the
WebApplicationBuilder instance.
The result, the app, represents the application itself. From this point, the
application is ready to set up routes, configure the middleware component, and
start handling requests, but it isn’t running yet.
This line defines a simple endpoint (or route) that handles HTTP GET requests.
So, you need to remember that using the Web Application instance, app, we can
set up the Middleware Component, endpoints, routing, etc. for our ASP.NET Core
Application
app.MapGet(“/”, …);: This maps the root URL (“/”) of the application to a
handler function.
When a user sends a GET request to the root URL (e.g., http://localhost/), this
route handler returns the string “Hello World!” as the response.
This is a basic HTTP route using the MapGet method, which allows us to handle
requests with a lambda function (() => “Hello World!”).
app.Run();:
This line starts the web server and begins listening for incoming requests.
Without app.Run(), the web server will not start. The Run() method keeps the
application running until manually stopped, and it is responsible for handling
incoming HTTP requests.
Note: Using the WebApplicationBuilder instance, we will configure the services,
and using the WebApplication instance, we will configure the Middleware
components required for our application.
The above example code configures a single endpoint using the MapGet method.
With the MapGet endpoint, when an HTTP GET request is sent to the application
root URL /, the request delegate executes, i.e., the statement () => “Hello
World!” will execute, and Hello World! will be written to the HTTP response.
Now, run the application, and you should get the following output, which is
coming from the MapGet Endpoint.
To prove it is a GET request, open the browser developer tool by pressing the
F12 key, go to the Network tab, and refresh the page. Then click on the local host,
and you will see the Request URL as https://localhost:7279/ and the Request
Method as GET, as shown in the image below.
With the MapGet endpoint, we can only send HTTP GET requests to the server
from the application root URL /. Now, let us add something to the URL and press
the enter button, as shown in the image below.
So, you need to remember that if the request method is not GET or the URL is not
/, then no route matches, and we will get an HTTP 404 Not Found Error.
Next=> The CreateBuilder method sets the web host with default configurations,
such as hosting the application with the default server (e.g., either IIS or Kestrel)
and the default hosting model (e.g., InProcess or OutOfProcess). So, next, we will
learn about Different Hosting Models.
What is the Hosting?
Hosting refers to the service that allows our web application to be
accessible over the Internet. When we develop a web application, we need a
server where our application’s files, databases, and other resources can
reside and be served to users who access our application via their web
browsers.
When executing an ASP.NET Core Web Application, the .NET Core Runtime looks
for the Main() method. The Main() method is the entry point for the .NET Core
Application to execute. As you can see in the above code, the Main() method of
the Program class calls the static CreateBuilder() method.
What are the Tasks Performed by the CreateBuilder() Method in ASP.NET Core?
The CreateBuilder() method sets up the Web Host to host the ASP.NET Core
application and configure the required services using default preconfigured
settings. As part of setting up the Web Host and configuring services, the
CreateBuilder() method performs several key tasks. Some of the important tasks
are as follows:
Set up Web Server (IIS, IIS Express, or Kestrel)
Host the Application (In-Process or Out-Of-Process)
Logging (debugging and console logging)
Configuration (How to access the Data from Configuration Files)
Dependency Injection Container (registering built-in and custom services)
What exactly does the CreateBuilder() method do to set up the Web Host?
The web host runs the ASP.NET Core application. It handles HTTP requests,
listens to configured URLs, and forwards requests to the application’s
middleware pipeline. Let us understand what exactly the CreateBuilder() method
does to configure and set up the Web Host. The CreateBuilder() method
Configures the Web Host with default settings to host the application.
When configuring the hosting model as InProcess and running the application
using the IIS Express launch profile, the ASP.NET Core application runs directly
within the IIS Worker Process (w3wp.exe or iisexpress.exe in
Development). This integration is more efficient than running the application in
a separate process because it eliminates the need for inter-process
communication between the web server and the application.
Because the application runs in the same process as IIS, there is no additional
overhead from network delays or context switching between the web server and
the application. This can lead to better response times and throughput, making it
ideal for high-performance-sensitive environments.
The process name used to execute the application code is w3wp in the case
of IIS. Similarly, if it is IIS Express, the process name will be iisexpress.
You are getting the above message from the following MapGet method, which is
present inside the Main method of the Program class, as shown in the image
below.
To display the name of the process that executes our application code in the
browser, we need to use
the System.Diagnostics.Process.GetCurrentProcess().ProcessName statemen
t within the Main method of the Program class. So, modify the Main method of the
Program class as follows.
Now, run the application from Visual Studio using the IIS Express profile. It
should display the following message in the browser, as shown in the image
below. This ensures that the IIS Worker Process executes the application code.
Microsoft developed the Kestrel web server as the default Cross-Platform Web
Server for hosting the ASP.NET Core Web Application on Windows, Linux, and
MacOS. Kestrel is designed to be lightweight, fast, and efficient, making it suitable
for both development and production environments.
ASP.NET Core LaunchSettings.json File
The launchSettings.json file in ASP.NET Core is a configuration file used to
configure how the application starts during development. It’s primarily used by
development tools like Visual Studio, Visual Studio Code, and the .NET CLI
(dotnet run) to configure how the application is launched during development.
It’s located in the Properties folder of an ASP.NET Core project.
The HTTP profile runs the application over HTTP without HTTPS and bypasses
IIS Express.
commandName: “Project” – This indicates that the application should be
run directly using the Kestrel server (bypassing IIS/IIS Express).
launchBrowser: true – If true, the browser will automatically open at the
application root URL when the project starts. If false, the browser will not
be opened.
environmentVariables – These are used to set environment variables that
are essential during the development phase. For example, the
ASPNETCORE_ENVIRONMENT variable can be set to Development, Staging,
or Production to simulate different environments on your development
machine.
dotnetRunMessages: true – This enables additional messages to be
displayed when the project is built and run using the .NET CLI.
applicationUrl – Specifies the URL for accessing the application here
“http://localhost:5066”.
Similar to the “http” profile, it includes configurations for both HTTP and HTTPS
protocols.
applicationUrl: “https://localhost:7107;http://localhost:5066” – This
means the application will listen on both HTTP (http://localhost:5066) and
HTTPS (https://localhost:7107). HTTPS is preferred for secure
communication.
IIS Express Launch Profile:
The IIS Express profile runs the application using IIS Express, a lightweight
version of IIS for development environments.
commandName: “IISExpress” – This indicates that the application will run
under IIS Express, a lightweight, self-contained version of IIS that is
optimized for the development environment.
launchBrowser: true – Automatically opens the browser to the application
URL when the project starts, similar to other profiles.
environmentVariables – Sets ASPNETCORE_ENVIRONMENT to
“Development”.
Note: The IIS Express profile allows testing of how the application behaves in an
IIS-hosted environment without deploying it on a full IIS server.
IIS Settings
The following are the settings that will be used by the IIS Express profile:
These settings are specific to IIS Express and affect how the application runs
when using the IIS Express profile.
windowsAuthentication: false – Indicates that Windows Authentication is
disabled. If set to true, Windows Authentication is enabled.
anonymousAuthentication: true – Specifies whether Anonymous
Authentication is enabled for your application. Setting it to true means any
user can access the application without credentials.
applicationUrl: http://localhost:53952 – Specifies the base URL for the
application under IIS Express, like “http://localhost:53952”.
sslPort: 44312 – Specifies the port to use for SSL (HTTPS) traffic when
using IIS Express. If the value is 0, the application cannot be accessed using
HTTPS.
Global Settings
$schema: This provides a URL
(http://json.schemastore.org/launchsettings.json) to a JSON schema that helps
IDEs validate the structure of launchSettings.json. This schema reference is useful
for JSON structure validation in editors like Visual Studio.
Important Points:
Profiles Usage: Each profile can be selected when running the application,
allowing developers to test the application in different environments (e.g., with
HTTP, HTTPS, or under IIS Express). You can switch between profiles using
Visual Studio or setting the appropriate launch settings in your terminal.
This file is typically divided into sections. For example, we might have sections
like ConnectionStrings, Logging, or custom sections for our application-specific
settings. Now, I will add a key named MyCustomKey within this file. To do so,
please modify the appsettings.json file as shown below. As it is a JSON file, we
need to store the value as a key-value pair.
Logging:
The Logging section configures the application’s logging behavior.
LogLevel: This subsection specifies the minimum log level for different
categories of loggers.
1. Default: “Information” – This sets the default log level to Information,
meaning logs at the Information level and above (e.g., Warning, Error,
Critical) will be recorded.
2. Microsoft.AspNetCore: “Warning” – This sets the log level specifically
for Microsoft.AspNetCore category to Warning, meaning that only
warnings, errors, and critical messages will be logged for components in
Microsoft.AspNetCore namespace.
AllowedHosts:
The AllowedHosts section specifies which hosts are allowed to make requests to
the application. This is typically used in scenarios where you want to restrict
access to certain domains. The “*” wildcard character means that any host is
allowed to access the application. You can restrict it by specifying a comma-
separated list of allowed hostnames, e.g., “example.com, localhost”.
MyCustomKey:
A custom section that we define for our own application
settings. “MyCustomKey”: “MyCustomKey Value coming from
appsettings.json”: This is a key-value pair where MyCustomKey is the key, and
MyCustomKey Value coming from appsettings.json is the value.
Logging Configuration
In this example, the logging levels are configured for the application and specific
namespaces.
External Service Configuration
This example shows how to store API settings for external services, like base
URLs and API keys.
Authentication Settings
Settings related to authentication, like JWT settings in this case.
ASP.NET Core Middleware Components:
ASP.NET Core Middleware Components are the basic building blocks of the
Request Processing Pipeline in ASP.NET Core Applications. The Request
Processing Pipeline determines how HTTP Requests and Responses will be
processed in the ASP.NET Core Application. So, middleware components are used
to implement various functionalities like authentication, authorization, error
handling, routing, and logging.
The following are some of the common built-in middleware components used in
ASP.NET Core applications:
UseRouting: Configures the routing middleware, which is responsible for
mapping incoming requests to the appropriate endpoint handlers based on route
patterns defined in the application. It allows the application to determine which
endpoint should handle the request and what the route parameters are.
Middleware components are executed in the order they are added to the pipeline,
and each middleware component in the ASP.NET Core Application performs the
following tasks.
Chooses whether to pass the HTTP Request to the next Middleware
component registered in the request processing pipeline.
Can perform certain tasks before and after the next component is invoked
in the pipeline.
Note: In ASP.NET Core, many built-in Middleware components are already made
available for us to use directly. We can also create our custom Middleware
components as per our business requirements. The most important point you
need to remember is that a given Middleware component should only have a
specific purpose, i.e., a single responsibility.
How Does the Middleware Component Works in the ASP.NET Core Application?
In the ASP.NET Core Web Application, the Middleware Component can access
both the incoming HTTP Request and outgoing HTTP Response. So, a
Middleware Component in ASP.NET Core Web Application can
Handle the incoming HTTP request by generating an HTTP response.
Process the incoming HTTP request, modify it, and then pass it to the Next
Middleware Component configured in the Request Processing Pipeline.
Process the outgoing HTTP response, modify it, and then pass it on to
either the previous middleware component or the ASP.NET Core Web
Server.
For a better understanding, please look at the following diagram, which shows
how the middleware components are used in the Request Processing Pipeline of
an ASP.NET Core Web Application. As shown in the image below, we have
configured 3 Middleware Components to handle HTTP Requests and Responses.
MapGet Method:
MapGet is specifically designed to handle HTTP GET requests. It’s used to
define endpoints that respond only to GET requests.
We typically use MapGet to retrieve data from the server without
modifying its state, such as fetching a list of items or getting details about a
specific item.
The MapGet method usually takes a route pattern and a request delegate (a
handler function). The handler function is executed when a GET request
matches the specified route pattern.
Map Method:
Map is a general method for handling all types of HTTP requests (such as
GET, POST, PUT, DELETE, etc.). It’s more flexible than MapGet.
We need to use Map when we need to set up endpoints that might handle
multiple types of HTTP requests or when we have custom logic to
determine the type of request to be handled.
Like MapGet, Map also takes a route pattern and a request delegate.
However, since Map can handle various HTTP methods, the request
delegate often contains logic to differentiate between these methods.
ASP.NET Core Request Processing Pipeline
The following diagram shows the complete request processing pipeline for
ASP.NET Core MVC, Web API, and Razor Pages application.
The above diagram shows the ASP.NET Core Request Processing Pipeline and the
sequence in which middleware components should registered and executed
when a request is processed in an ASP.NET Core application. Let us understand
each step in the Request Processing Pipeline:
Request: This is where the incoming HTTP request enters the pipeline. Each
middleware component in the pipeline can inspect, modify, or pass the request to
the next component.
Static Files: This middleware enables static files like HTML, CSS, JavaScript, and
images to be served directly without passing them through the rest of the
pipeline. This is useful for files that don’t need processing.
Routing: This middleware maps the incoming request to a route, allowing the
application to handle it appropriately. Based on URL patterns and route
configurations defined in the application, this middleware determines which
controller and action will handle the incoming HTTP request.
Endpoint: This is the target of the request, such as a controller action in MVC,
Web API, or a Razor Page. The endpoint processes the request and generates a
response.
Response: After the endpoint generates a response, it goes back through the
pipeline, allowing each middleware component to modify it before sending it
back to the client.
Example to Understand ASP.NET Core Request Processing Pipeline
To understand the Request Processing Pipeline in ASP.NET Core Web
Application, first, let us modify the Main() Method of the Program class as shown
below.
Here, we are registering three middleware components into the Request
Processing Pipeline. As you can see, the first two middleware components are
registered using the Use() extension method, so they have the chance to call the
next middleware component in the request processing pipeline.
The last one is registered using the Run() Extension Method as it will be our
terminating components, i.e., it will not call the next component.
Now run the application, and you should get the following output in the
browser.
Understanding ASP.NET Core Request Processing Pipeline Execution Order:
Let us compare the above output with the following diagram to understand the
ASP.NET Core Request Processing Pipeline more easily.
When the incoming HTTP request arrives, it is first received by the first
middleware component, Middleware1, which logs “Middleware1: Incoming
Request” in the response stream. As a result, we first see this message on the
browser. Once the first middleware logs the information, it calls the next()
method, invoking the second middleware in the request processing pipeline,
Middleware2.
The third middleware handles the request and then produces the response. So,
the third information that we see in the browser is “Middleware3: Incoming
Request handled and response generated”.
The third middleware component is registered using the Run() Extension Method
and is a terminal middleware component. So, from this point, the request pipeline
starts reversing. That means the control is returned to the second middleware
from this middleware. The second middleware logs the information as
“Middleware2: Outgoing Response” and then gives the control back to the first
middleware component, and the first middleware component logs the
information as “Middleware1: Outgoing Response” as we see in the browser.
The most important point is that the order in which the Middleware Components
are added in the Main method of the Program class defines the order in which
these Middleware Components will be invoked on requests and the reverse order
for the response. So, the order is critical for defining the application’s Security,
Performance, and Functionality.
wwwroot Folder in ASP.NET Core
In ASP.NET Core, the wwwroot folder is the designated Web Root directory
where static files are stored and served to clients. This folder, located in the
project root by default, contains static assets like images, CSS, JavaScript, and
other resources accessible to clients via direct URLs.
Generally, there should be separate sub-folders for the different types of static
files, inside the wwwroot folder such as:
CSS for stylesheets,
js for JavaScript files,
images for images,
lib for libraries (e.g., third-party scripts).
For a better understanding about folder structure, please have a look at the
following image.
Now, you can access static files such as CSS, JS, and lib with the base URL and file
name. For example, you can access the above site.js file from the js folder
by https://localhost:<port>/js/site.js
Note: To serve these static files, include the UseStaticFiles() middleware in the
Main method of the Program.cs file.
UseDirectoryBrowser, UseStaticFiles, UseFileServer, and UseDefaultFiles Middleware
Components
Let us Modify the Program class, as shown below, to register the UseStaticFiles()
Middleware Component in the application’s Request Processing Pipeline.
Serving the File: If a matching file is found, the middleware sends it directly to
the client. The file is sent with appropriate headers, including Content-Type,
based on its extension.
Return Not Found (404): If the requested file is not found in the wwwroot (or
custom) folder, the pipeline can then handle the request as needed (e.g.,
returning a 404 page).
So, the UseStaticFiles() middleware in ASP.NET Core serves static files efficiently
by intercepting requests, matching paths, and serving files directly to clients from
the designated static file directory (default is wwwroot).
So, please modify the Program class as shown below to use the UseDefaultFiles()
middleware component.
With the above changes in place, now run the application, and you should see the
output as expected, as shown below. That index.html page serves as your default
page.
It generates an HTML page displaying the files and folders within the specified
directory when enabled. This middleware is useful for development and
debugging purposes, as it lets developers explore the files directly on the server,
though it’s typically not recommended in production for security reasons.
By default, ASP.NET Core doesn’t enable directory browsing. You can enable it by
adding the UseDirectoryBrowser middleware component to the application
pipeline. Let us understand this with an example.
Please modify the Main method of the Program class as follows. Here, I am using
the UseDirectoryBrowser Middleware Component.
Now, run the application. When you visit the root URL, you will see the directory
structure of the wwwroot folder, as shown in the image below.
Now, run the application. It will display the Index.html page by default when you
access the root URL, as shown in the image below.
Differences Between UseDirectoryBrowser, UseStaticFiles, UseFileServer,
and UseDefaultFiles
UseStaticFiles
Serves static files such as HTML, CSS, JavaScript, and images directly to clients.
Serves files from the wwwroot folder by default. Responds to requests matching
the file’s URL path directly without additional processing.
Use UseStaticFiles when you only need to serve static content (e.g., CSS, JS,
images) without requiring a default file or directory browsing.
UseDefaultFiles
Use UseDefaultFiles with UseStaticFiles if you want a specific default file (like
index.html) to be served automatically when accessing a directory URL.
UseDirectoryBrowser
Enables directory browsing, allowing users to see and navigate the contents of
directories on the server. It generates an HTML page showing the directory’s
contents, allowing users to view and download files directly. It should only be
used in development or trusted internal environments, as it exposes all files
within a directory to users.
UseFileServer