0% found this document useful (0 votes)
3 views90 pages

Unit-1 Net Core Framework

The document outlines the curriculum for a Master's course on the .NET Core Framework at CVM University, covering key topics such as ASP.NET Core, MVC pattern, controllers, views, model binding, and state management. It highlights the advantages of ASP.NET Core, including its cross-platform capabilities, high performance, and modular architecture. Additionally, it compares ASP.NET Core with previous frameworks and discusses the support policy and differences between .NET Framework and .NET Core.

Uploaded by

suchitab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views90 pages

Unit-1 Net Core Framework

The document outlines the curriculum for a Master's course on the .NET Core Framework at CVM University, covering key topics such as ASP.NET Core, MVC pattern, controllers, views, model binding, and state management. It highlights the advantages of ASP.NET Core, including its cross-platform capabilities, high performance, and modular architecture. Additionally, it compares ASP.NET Core with previous frameworks and discusses the support policy and differences between .NET Framework and .NET Core.

Uploaded by

suchitab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

CVM UNIVERSITY

INSTITUTE OF SCIENCE & TECHNOLOGY FOR ADVANCED STUDIES & RESEARCH (ISTAR)
M.Sc. (Information Technology)
Semester – II

Paper Code: 101410212


Paper Title: .NET CORE FRAMEWORK

Prepared By:
Dr. Suchita Patel
Assistant Professor
M.Sc. (IT) Department, ISTAR

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
ASP.NET Core – Introduction & Environment Setup
ASP.NET Core Basics

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

Unit 4: Model Binding: Html Form behaviour; Model Binder Overview;


DefaultModelBinder; Binding to Complex Classes ; IFormCollection Model
Binding; IFormFile Model Binder; Bind Attribute ; TryUpdateModelAsync; State
Management Techniques: Cookies; Session Security: Authentication and
Authorization MVC and Entity Framework Core: Basic CRUD Operations using
Entity Framework
ASP.NET Core MVC – Model Binding
ASP.NET Core MVC – State Management

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.

Overview of Microsoft Web Technologies

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 Web Forms:


ASP.NET Web Forms is one of Microsoft’s earlier frameworks, introduced
in 2002 with the .NET Framework 1.0. It is designed for building dynamic,
data-driven web applications using a drag-and-drop, event-driven
programming model similar to Windows Forms.

Current Status: ASP.NET Web Forms is considered legacy technology and is no


longer actively developed. For new projects, Microsoft recommends using
ASP.NET Core.

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.

ASP.NET Web API:


ASP.NET Web API is a framework for building HTTP-based services that can be
consumed by various clients, including browsers, mobile devices, and desktop
applications. These HTTP services can return data in various formats, including
JSON and XML. ASP.NET Web API was released in 2012 as part of the .NET
framework 4. So, ASP.NET Web API is a framework introduced to build
RESTful HTTP services, enabling communication between clients (like
browsers or mobile apps) and servers using HTTP.
Note: ASP.NET Web API has been unified into ASP.NET Core as part of ASP.NET
Core Web API. For new projects, using ASP.NET Core Web API is recommended
to take advantage of cross-platform support and improved performance.

ASP.NET Core MVC:


ASP.NET Core MVC is a cross-platform, open-source framework for building
modern, cloud-optimized, and high-performance applications following the
Model-View-Controller (MVC) design pattern. It is part of ASP.NET Core, which
was first released in 2016 as a complete rewrite of ASP.NET to support cross-
platform development and improved performance.
Note: ASP.NET Core MVC is actively developed and is the recommended
framework for new web application projects. It represents the future direction
of Microsoft’s web development stack.

ASP.NET Core Web API:


ASP.NET Core Web API is a framework for building HTTP-based services in
ASP.NET Core, designed for cross-platform and high performance. It is best
suited for building RESTful services with high performance and cross-platform
capabilities.
Note: ASP.NET Core Web API is actively maintained and recommended for
building modern, scalable, and high-performance APIs. It benefits from the
ongoing enhancements in the ASP.NET Core ecosystem.

ASP.NET Core Razor Pages:


ASP.NET Core Razor Pages is a page-based programming model introduced in
ASP.NET Core 2.0 (2017). It simplifies web application development by
enabling a page-focused approach, where each page handles its own actions
and view logic. Unlike MVC, Razor Pages focuses on individual pages, making it
easier to build simple web applications.
Note: ASP.NET Core Razor Pages is actively developed and widely adopted for
scenarios where a page-based architecture is beneficial.

ASP.NET Core Blazor:


ASP.NET Core Blazor is a modern framework introduced with .NET Core 3.0 in
2019 that allows developers to build interactive web applications using C#
instead of JavaScript. It is ideal for .NET developers looking to build interactive
client-side Web UIs with .NET without relying on JavaScript. Blazor has two
modes of operation:
 Blazor Server: Runs on the server, and updates are sent to the browser
via SignalR.
 Blazor WebAssembly: Runs in the browser using WebAssembly
(WASM), allowing developers to write rich, client-side web applications
in C#.
Note: Blazor is actively developed and rapidly gaining popularity as a modern
framework for building interactive web applications. Microsoft continues to
invest heavily in Blazor, adding new features and improving performance. It
represents a significant shift towards full-stack .NET development.

Choosing the Right Framework


Selecting the appropriate Microsoft web technology depends on various
factors, including project requirements, team expertise, performance needs,
and future scalability:

 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

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.

ASP.NET Core is a cross-platform, open-source framework for building


modern web applications. It’s a redesign of the older ASP.NET framework,
offering better performance, flexibility, and support for cloud-based and
containerized applications.
Key Features of ASP.NET Core:

1. Cross-Platform – Runs on Windows, Linux, and macOS.


2. High Performance – Faster than traditional ASP.NET due to the Kestrel web server and
optimized request pipeline.
3. Modular & Lightweight – Uses a dependency injection system and middleware-based
request processing.
4. Built-in Dependency Injection – Supports IoC (Inversion of Control) for better
maintainability.
5. Razor Pages & MVC – Supports both Razor Pages (for simple web pages) and MVC (for
structured applications).
6. Minimal APIs – Allows for lightweight API development with minimal boilerplate code.
7. Blazor – Enables full-stack web development using C# instead of JavaScript.
8. Authentication & Authorization – Supports Identity, OAuth, JWT, and external
providers like Google & Facebook.
9. Cloud & Microservices Support – Works well with Docker, Kubernetes, and Azure.
10. Middleware Pipeline – Uses custom middleware for handling requests.

Why ASP.NET Core?


Nowadays, the ASP.NET Core framework is becoming more and more popular
among developers. There are a number of reasons why developers are using it,
and some of them are listed below:

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.

Compared with Traditional ASP.NET Framework, earlier versions of ASP.NET


Framework applications can only run on Windows platforms. On the other hand,
ASP.NET Core applications can be developed and run on different platforms, such
as Windows, Mac, or Linux operating systems. We can host the earlier ASP.NET
Framework applications only on IIS, whereas we can host the ASP.NET Core
applications on IIS, Nginx, Apache, or within Docker containers.

Lightweight and Modular:


The framework is built to be modular, which allows developers to include only
the necessary libraries. This reduces the application’s overall size and improves
performance. Dependencies are managed via NuGet packages, making it easy to
add or remove features.

Built-in Dependency Injection:


ASP.NET Core includes a built-in dependency injection (DI) container. This
feature simplifies the management of service lifetimes and dependencies, leading
to more maintainable and testable code.

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.

Differences Between .NET Framework vs .NET Core Framework


The following are the Differences Between .NET Framework and .NET Core
.NET Framework
 Platform: Designed exclusively for Windows.
 Architecture: Monolithic, including all features by default, leading to larger
applications.
 Performance: Does not match the performance optimizations of .NET Core
due to its older architecture.
 Support and Development: In maintenance mode with Microsoft
primarily releasing security updates and critical fixes; no new features are
being added.
 Open Source: It is not open source.
 Use Cases: Ideal for applications tightly integrated with the Windows
ecosystem, such as desktop applications, or for maintaining large existing
applications built on the .NET Framework.
.NET Core
 Platform: Cross-platform, running on Windows, Linux, and macOS.
 Architecture: Modular, allowing developers to include only necessary
packages via NuGet, resulting in lighter and more efficient applications.
 Performance: Optimized for high performance and scalability.
 Support and Development: Actively developed with regular additions of
new features, performance improvements, and enhancements.
 Open Source: It is open source and hosted on GitHub with over 100,000
contributions from more than 3,700 companies.
 Use Cases: Perfect for building modern web applications, microservices,
and applications requiring cross-platform functionality.

.NET Core (.NET) vs ASP.NET Core:


Many people are confused between ASP.NET Core and .NET Core. Please note that
ASP.NET Core and .NET Core are not the same. They are different, just like
ASP.NET and .NET Framework are different.

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:

.NET Core (.NET):


 .NET Core (.NET) is the cross-platform software. It provides the Runtime
Environment where the ASP.NET Core Web Applications will run.
 Install .NET Core Runtime to run applications and install .NET Core SDK to
build applications.
 .NET 8 is the latest stable version.

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.

Integrated Development Environment (IDE):


You can choose from various IDEs for ASP.NET Core development, including:
 Visual Studio 2022: Highly recommended for Windows users. It provides
comprehensive support for .NET development, including project templates,
a powerful debugger, and direct integration with SQL Server Management
Studio. Visual Studio is available for Windows and macOS.
 Visual Studio Code: Visual Studio Code is a lightweight, cross-platform
code editor supporting ASP.NET Core development. It offers excellent
extension support, integrated terminal, and source control integration.
Visual Studio Code is available for Windows, macOS, and Linux.

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

Database Management System:


You need a database management system depending on your application’s
requirements. Common options for ASP.NET Core include:
 Microsoft SQL Server: This is a popular choice for Windows
environments, especially in enterprise applications. It integrates easily
with Visual Studio and ASP.NET Core.
 MySQL or PostgreSQL: Good alternatives for macOS or Linux
environments or for developers looking to work with open-source
databases.
 SQLite: It is a lightweight and file-based database system suitable for
development and small-scale applications.

SQL Server Management Studio (SSMS):


SQL Server Management Studio (SSMS) is an integrated environment for
managing SQL Server databases. It offers tools for configuration, administration,
and design.

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.

What is Visual Studio?


Visual Studio is an integrated development environment (IDE) created by
Microsoft. It is the one-stop shop for all applications built on the .NET platform.
Using Visual Studio, we can develop, debug, and run .NET Core applications. It is
used to develop Windows, Web Applications, mobile apps, and cloud services
applications.
Now, let us proceed and understand the step-by-step process of downloading and
Installing Visual Studio. I am going to show you how to Download and Install
Visual Studio 2023 on the Windows Operating System.

How to Download and Installed Visual Studio on Windows OS?


To Download and Installed Visual Studio on a Windows operating system, we
need to follow the below steps:
 Visit the Official Microsoft Website: Visit the Visual Studio official
website.
 Choose the Edition: Select the edition of Visual Studio you need. Several
editions are available, including Community (free), Professional, and
Enterprise (both require a subscription).
 Download the Installer: Click the “Download” button for your chosen
edition. This will download the Visual Studio Installer executable file.
 Run the Installer: Double-click the downloaded installer file to start the
installation process.
 Install Required Workloads: During the installation, you can choose
different workloads, which are sets of features needed for different kinds of
development (e.g., desktop, web, mobile development).
 Complete Installation: Follow the on-screen instructions to complete the
installation.

Download Visual Studio’s Latest Version


In order to Download Visual Studio’s Latest Version, please visit the following
Visual Studio download link:
https://visualstudio.microsoft.com/downloads/
Visual Studio 2022 comes in three different editions: Community, Professional,
and Enterprise. Each edition is designed for different user needs and comes with
varying features, tools, and licensing terms. The following are the key differences
between these three editions:

Visual Studio 2022 Community Edition


 Target Audience: Individual developers, students, open-source
contributors, and small teams.
 Price: Free.
 Features: Offers most of the core features necessary for developing
applications, including support for various programming languages,
debugging tools, version control integration, and more.
 Limitations: It can be used for commercial development in organizations
with no more than five users. Larger organizations can use it only for open-
source projects, academic research, and classroom learning.

Visual Studio 2022 Professional Edition


 Target Audience: Professional developers and small to medium-sized
teams.
 Price: This requires a paid subscription. Prices vary depending on whether
the license is standalone or part of a Visual Studio subscription, which
includes additional benefits like Azure credits and access to other Microsoft
software.
 Features: It includes all features of the Community edition plus additional
tools and services for more robust development needs.
 Usage: No restrictions on the size of the organization or the number of
users.
Visual Studio 2022 Enterprise Edition
 Target Audience: Large development teams and organizations needing
advanced and scalable development tools.
 Price: Requires a more expensive subscription compared to the
Professional edition.
 Features: Includes all features of the Professional edition, plus advanced
debugging, performance profiling tools (such as IntelliTrace and Code
Map), Live Dependency Validation, and more. It also includes
comprehensive testing tools (like Live Unit Testing and Test Impact
Analysis), advanced code analytics, and optimization tools.

If you are a student or want to learn .NET, you can select the Community Edition,
which is absolutely free.

Open the .exe file.


Click on the downloaded EXE file as shown in the below image.

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.

Start the Visual Studio Installation


Once you click the Yes button in the previous step, the following window will
open. From this screen, click the continue button to start the Visual Studio
installation, as shown in the image below.
Once you click on the Continue button, Visual Studio will start downloading the
initial files. The download speed will vary depending on your internet
connection. Let the installation complete, as shown in the image below.

Select the Visual Studio Features:


Once the initial files are downloaded, you will get the following Visual Studio
installer screen. Here, I am selecting two checkboxes.
1. ASP.NET and Web Development: For developing WEB Based application
2. .NET Desktop Development: For developing Console, Windows Form,
WPF Applications
Once you select the above two checkboxes from the workload section, click the
Install button, as shown in the image below.
Wait for the files to be downloaded.
Once you click the Install button, Visual Studio will download the relevant files
based on the features you selected in the previous step. This will take some time
to download the required files. You can monitor it the same way shown in the
image below.

Sign in to Visual Studio


Once the download is completed, you will see a screen asking you to sign in to
Visual Studio. You can sign in now or later using your Microsoft Account.
Open Visual Studio
Open the Visual Studio IDE. When we open it for the first time, it will ask you to
select the theme of your choice and then click on the Start Visual Studio Button,
as shown in the image below.
That’s it. Now you are ready to develop .NET Applications using C# language in
Visual Studio. In Visual Studio IDE, you can create new C# applications by clicking
Create a new project option, as shown in the image below.

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.

Visual Studio Key Features


The following are the key features of Visual Studio:
 Multi-Language Support: The Visual Studio IDE can be used to develop
.NET applications using any .NET .NET-supported programming language
such as C#, VB, F#, etc.
 Creation of any application type: The Visual Studio IDE can be used to
develop different types of .NET applications, such as Web-based or
Windows Forms-based applications, Console Applications, and Web APIs.
 Integrated Development Server: Includes IIS Express for Web
Development, enabling easy testing and development of web applications.
 Code Editor: It provides the code editor with syntax highlighting, code
completion, and code navigation features.
 Debug Applications on the fly: Applications can be tested as they are
being built. The IDE allows one to run the program at any point during the
development process so that a developer can check for errors during the
development phase.
 Version Control Integration: Integrates with Git and other version
control systems directly within the IDE.
 Database Tools: Includes SQL Server Object Explorer, which allows for the
management of SQL databases within the same environment.
 Extensions: The IDE has the facility to install third-party extensions.
How to Download and Install .NET Core SDK
Follow the below steps to download and install the .NET Core SDK. These steps
apply to various operating systems, including Windows, macOS, and Linux.
 Visit the Official .NET Website: Go to the .NET download page to find the
latest version of the .NET SDK.
 Choose Your Version: Select the .NET SDK version you wish to download.
If you are not sure which version to install, it is usually best to choose the
most current stable release.
 Download the Installer: Click the Windows installer link to download the
.NET SDK installer. This will be a .exe file.
 Run the Installer: Once the download is complete, run the downloaded file
and follow the instructions on the installer to complete the installation.
 Verify the Installation: Open a Command Prompt or terminal and run the
following command to verify that .NET has been installed correctly.
The dotnet –version command will display the latest installed .NET
version.

Download .NET Core SDK:


To download .NET 8 SDK, go to the following website, and you will find the link to
download .NET 8 SDK for different OS.
https://dotnet.microsoft.com/en-us/download/dotnet/8.0
Once you visit the above URL, it will open the below page. Select the appropriate
link to download the .NET 8 SDK for the respective OS. After downloading the
installer, click on it to start the installation.

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.

Installing .NET Core SDK:


Once you download the .NET SDK, install it by double-clicking the downloaded
exe file. Once you click on the EXE, it will open the following window. In this
window, click on the Install button, as shown in the image below.
If everything is fine, once the installation is completed, you will get the following
message saying the installation was successful: Click on the Close button, as
shown in the image below.

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.

Verify the Installation of .NET SDK:


Once you installed .NET SDK, open the command prompt type dotnet, and press
the enter key as shown in the below image. If the installation succeeds, you
should get the following output:
Now, to verify what versions are installed on your machine, type the dotnet –
info command in the command prompt and press the enter button, as shown in
the image below.

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.

The MVC Design Pattern is used to develop interactive applications. An


interactive application involves user interaction, and based on the user
interaction, some event handling occurs. The most important point you need to
remember is that it is not only used for developing Web-Based Applications; we
can also use this MVC Design Pattern to develop Desktop or Mobile-Based
applications.

The MVC (Model-View-Controller) Design Pattern was introduced in the 1970s. It


divides an application into three major components: Model, View, and Controller.
The main objective of the MVC Design Pattern is the separation of concerns. This
means the Domain Model and Business Logic are separated from the User
Interface (i.e., View). As a result, maintaining and testing the application become
simpler and easier.

How Does MVC Design Pattern Work in ASP.NET Core?


Let’s look at an example to understand how the MVC Design Pattern works in an
ASP.NET Core MVC application. We want to design an application that displays
the student details on a web page, as shown below.

So, when we request something


like https://localhost:7132/Student/Details/2 from a web browser, the
following things happen to handle the request.
The Controller is the Component in the MVC design pattern that handles the
incoming request. The controller components do several things to handle the
request. The controller component creates the model that is required by a view.
The model is the component in the MVC design pattern, which basically contains
classes that are used to store the domain data or, you can say, business data. In
the MVC design pattern, the Model component also contains the required logic to
retrieve data from a database.

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.

Role of Model in MVC Design Pattern:


The Model in an MVC application represents the application’s state and business
logic. That means the Model is the component in the MVC Design pattern used to
manage the data, i.e., the application’s state in memory. The Model represents a
set of classes used to describe the application’s validation, business, and data
access logic. So, in our example, the model consists of Student and
StudentBusinessLayer classes.
In our example, we use the Student class to hold the student data in memory. The
StudentBusinessLayer class manages the student data, performs the CRUD
operation, Validates the Student data, etc.

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.

Key Responsibilities of Models:


 Retrieve and store data in the database or other storage mechanisms.
 Provide data to the controller as needed.
 Respond to instructions from the controller to update itself (e.g., updating
data points).

Role of View in MVC Design Pattern:


The View is the Component in the MVC Design pattern that contains the logic to
represent the model data as a user interface with which the end-user can
interact. Basically, the view renders the domain data (i.e., business data)
provided by the controller. There should be minimal logic (you should not write
any business logic, calculation logic, validation logic, etc.) within views, and any
logic in them should only be related to presenting the content.

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.

Key Responsibilities of Views:


 Display the data provided by the controller in a format suitable for
interaction.
 Send user inputs (like button clicks or data entries) to the controller.
 Update the visual presentation when the data in the model changes.

Role of Controller in MVC Design Pattern:


The Controller is the component in an MVC application that handles the incoming
HTTP Request. Based on the user action, the respective controller might work
with the model, select a view to render the information, and then send the
response back to the user who initially made the request. So, the Controller is the
component that will interact with both the models and views to control the
application execution flow.
In ASP.NET Core MVC Application, a Controller is a .cs (for C# language) file with
some methods called Action Methods. When a request comes on the controller,
the controller’s action method handles those requests. In our example, when the
user issued a request, the following URL

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.

Key Responsibilities of Controllers:


 Handle user input and convert it to commands for the Model or View.
 Decide what response to send back to a user when a user makes a browser
request.
 Update the Model when the user manipulates it through the View.
 Select the appropriate View to present the data from the Model.

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.

Features of ASP.NET Core MVC:


The ASP.NET Core MVC Framework comes with some amazing features. They are
as follows:
 Open Source: The ASP.NET Core MVC Framework is open source, which is
the main reason for its popularity. The Entire Source Code of ASP.NET Core
MVC Framework is available at https://github.com/aspnet, and you are
free to download the source code; even if you want, you can also modify
and compile your own version.

 Built-In Dependency Injection: ASP.NET Core has built-in support for


dependency injection, which helps manage dependencies between objects,
making the system more modular, scalable, and testable.

 Rich Routing: ASP.NET Core MVC provides a robust routing mechanism


that allows developers to control web application URLs. It supports
pattern-based URL mapping, which helps define SEO-friendly URLs.

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

 Extensive Built-In Middleware: The framework provides extensive built-


in middleware components that can handle requests for authentication,
routing, session state, and more. Developers can also create custom
middleware.

 Tag Helpers: Tag Helpers enable server-side code to participate in creating


and rendering HTML elements in Razor files.
Creating ASP.NET Core Web Application using Visual Studio
Now, we will create the ASP.NET Core Application using .NET 8. To create a new
ASP.NET Core Application using .NET 8, open Visual Studio 2022 and click the
Create a new project box, as shown in the image below.

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.

Understanding Configure Your New Project Window:

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

Place solution and project in the same directory:


If you check this box, Visual Studio will store both the solution and project files in
the same directory. By default, this checkbox is unchecked, and Visual Studio
creates a separate folder for the solution and then a subfolder for the project
inside that solution folder. This approach is useful if you plan to add multiple
projects to the same solution in the future.

Project will be created in:


This label shows the full path on which the project will be created. In our case,
the project will be created
in: D:\Projects\FirstCoreWebApplication\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.

Configure for HTTPS


This checkbox is used to configure your project to use HTTPS. When this option is
checked, indicating that the project will be configured to use HTTPS by default,
which is essential for secure communication between the server and clients. It is
highly recommended for production environments. Visual Studio will add the
necessary SSL settings to your ASP.NET Core project here.

Enable Container Support


This option allows us to add Docker support to our project, enabling
containerization. This option is unchecked, meaning containerization support is
not enabled for the project. If checked, we could run the project inside a container
such as Docker, useful for microservices, cloud-based deployments. If enabled,
we also have to select the container OS.

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.

Container Build Type


This dropdown also becomes available if “Enable container support” is checked.
It allows us to choose between Dockerfile and .NET SDK. As you can see by
default, Dockerfile is selected as the build type but is also disabled since
container support is not enabled. When enabled, this option specifies that a
Dockerfile will be used to build the container image.

Do not use top-level statements


Checking this option means that the project will not use top-level statements.
Top-level statements are a feature introduced in C# 9.0 that simplifies the
program structure by allowing us to omit the Main method when writing simple
applications. Checking this box means we will follow the traditional program
structure, where the Main method is explicitly defined.
Enlist in .NET Aspire Orchestration
This option is related to Azure or a DevOps process. If unchecked, the project will
not be part of the .NET Aspire orchestration. This orchestration feature is
provided in certain environments for managing complex deployments,
particularly for Azure or cloud-based deployment automation.

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.

Understanding the Project Files:


Connected Services:
This folder provides a way for our application to connect to external services like
Azure, REST APIs, WCF services, or Database connections. It helps us integrate
external functionality into our application without manual configurations.
Currently, it’s empty because no services have been added yet.

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.

Run ASP.NET Core Application:


To run this ASP.NET Core Web Application, click on IIS Express or press F5 (with
debugging) or Ctrl + F5 (without debugging). This will open the browser and
display the following output.

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.

Project Templates in ASP.NET Core


As you can see in the below image, while creating ASP.NET Core Application, we
have different types of project templates for creating ASP.NET Core Web
applications.
Let us understand what all these project templates are and their use.

ASP.NET Core Web App (Razor Pages)


 The ASP.NET Core Web App project template uses Razor Pages, which is a
page-based programming model for building Web UIs. Razor Pages
simplifies the development of page-focused scenarios by allowing
developers to define page-specific logic within the same file as the HTML
markup.
 It is suitable for building web applications with a simpler structure, where
each page is self-contained and designed to handle requests and responses
directly.
ASP.NET Core Empty
 The ASP.NET Core Empty project template creates a minimal ASP.NET Core
application with no predefined folders or files. It allows developers to add
only the components and middleware they need.
 It is ideal for advanced users who want complete control over the project
structure and dependencies or for creating highly customized applications
from scratch.

ASP.NET Core Web API


 The ASP.NET Core Empty project template is designed to create RESTful
HTTP services. It includes predefined folders and files for creating and
managing API endpoints and is configured with the necessary middleware
for building Web APIs.
 It is best suited for building backend services that expose data and
functionality through HTTP endpoints intended for consumption by client
applications such as web, mobile, or desktop apps.

ASP.NET Core Web API (Native)


 The ASP.NET Core Web API (Native) project template is similar to the
standard Web API template but optimized for running natively on various
platforms. It includes additional configurations and dependencies to use
native platform capabilities.
 It is useful for developers looking to build APIs that can be deployed and
run natively on specific platforms with optimized performance.

ASP.NET Core Web App (Model-View-Controller)


 This project template uses the Model-View-Controller (MVC) architectural
pattern. It separates an application into three main components: Models
(data), Views (UI), and Controllers (business logic).
 It is suitable for building complex web applications with a clear separation
of concerns, where the application logic, UI, and data access layers are
distinct.
Blazor Server App
 The Blazor Server App Project template creates a Blazor Server application.
Blazor Server allows for the development of interactive web UIs using C#
instead of JavaScript. The app runs on the server, with UI updates sent to
the client via SignalR.
 It is ideal for building real-time, interactive web applications where the
client-side logic needs to be executed on the server, ensuring consistent
behavior and reducing client-side resource requirements.

Blazor WebAssembly App


 The Blazor WebAssembly App Project template creates a Blazor
WebAssembly application. Blazor WebAssembly runs C# code directly in
the browser using WebAssembly. The entire app, including .NET runtime, is
downloaded and executed on the client side.
 It is suitable for building single-page applications (SPAs) that run entirely
in the browser, providing a rich, responsive user experience similar to
JavaScript frameworks like Angular or React.

Razor Class Library


 The Razor Class Library project template creates a library containing
reusable Razor UI components. These components can be shared across
multiple projects, promoting code reuse and modularity.
 It is ideal for developing UI components, such as layouts, partial views, and
Razor Pages, that can be packaged and reused in different ASP.NET Core
applications.
ASP.NET Core MVC Complete Folder Structure

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.

2. wwwroot/ (Static Files)

 Stores static content like:


o CSS, JavaScript, and image files.
o Third-party libraries (e.g., Bootstrap, jQuery).
 These files are accessible to the browser and do not require a controller
action.

3. Controllers/ (Business Logic)

 Contains controller classes that handle HTTP requests and return


responses.
 Controllers follow the convention {ControllerName}Controller.cs (e.g.,
HomeController.cs).
 They define action methods that process user input and return views or
data.
Example HomeController.cs:

4. Models/ (Data and Business Logic)

 Contains data models used in the application.


 Models are plain C# classes (POCOs) that define data properties and
validation logic.

Example Product.cs:

5. Views/ (UI - Razor Templates)

 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:

 _Layout.cshtml (Located in Shared/)


o Defines a common layout for all views (e.g., header, footer,
navigation).
 _ViewStart.cshtml
o Defines a default layout for views.
 _ViewImports.cshtml
o Includes common namespaces, tag helpers, and configurations for
views.

6. Data/ (Optional - Database Context)

 Often contains the Entity Framework Core DbContext for database


interactions.
Example ApplicationDbContext.cs:

7. Migrations/ (Optional - EF Core Migrations)

 Contains Entity Framework Core migration files, which track database


schema changes.

8. Services/ (Optional - Business Logic Services)

 Stores application services, such as repository classes or business logic.


ASP.NET Core Project File
If you have worked with the previous versions of ASP.NET Framework, then you
may know that while creating a Project in Visual Studio, it creates a project file
for us.

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.

How Can We Edit the Project File in Previous Versions of ASP.NET?


In our previous versions of the ASP.NET Framework, we needed to follow the
steps below to edit the project file.
1. First, we need to unload the project
2. Then, we need to edit the project file using Notepad
3. Once we edit the project file then, we need to save the project file
4. Then, reload the project.
However, with ASP.NET Core (.NET), we can edit the project file without
unloading the project.

How we can Edit the ASP.NET Core Project File:


To edit the ASP.NET Core project file, right-click on the project name in the
Solution Explorer and then select Edit Project File from the context menu, as
shown in the image below.
Once you click on Edit Project File, the Project file will open in the Visual Studio
editor, as shown in the image below.

Understanding the ASP.NET Core Project File:


The .csproj file is an XML file that contains information about your project, such
as its dependencies, build configuration, target framework, and other settings. Let
us understand the above settings:

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

The ImplicitUsings setting is enabled. This feature, introduced in .NET 6,


automatically includes commonly used using directives (e.g., System,
System.Collections.Generic, System.Linq, Microsoft.AspNetCore.Http, etc.)
without explicitly adding them to every file. This makes the project files cleaner
and ensures that standard namespaces are included without requiring manual
addition to each file.

Adding Packages in ASP.NET Core:


As we already discussed, the ASP.NET Core Framework follows a Modular
approach. This means that by default, it will not include anything, i.e., package
references to the project. Only the necessary packages are added by default.

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:

 <PackageReference Include=”Newtonsoft.Json” Version=”13.0.3″ />:

This element specifies a package reference to the Newtonsoft.Json NuGet


package, version 13.0.3. The Newtonsoft.Json package is a popular JSON
framework for .NET that is used to serialize and deserialize JSON data. By
including this package reference, the project can use the functionality provided
by Newtonsoft.Json.

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:

 Creating the Web Host and Configuring the Services


 Building the Application
 Setting Up Endpoints, Routing, and Middleware Components
 Running the Application

Let us understand the Main method in detail:

Step 1: Creating the Web Host and Configuring the Services

var builder = WebApplication.CreateBuilder(args);:

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.

The WebApplicationBuilder instance is responsible for configuring essential


services (like Logging, Configuration, MVC, Web API, Dependency Injection, etc.)
preconfigured defaults such as:

 Set up Web Server (IIS, or Kestrel)


 Host the Application (InProcess or OutOfProcess)
 Logging (debugging and console logging)
 Configuration (How to access the Data from Configuration Files)
 Dependency Injection Container (registering built-in and custom services)

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.

Step 2: Building the Application


var app = builder.Build();:
After configuring the essential services, when the Build() method is called on the
WebApplicationBuilder instance, the actual WebApplication instance is built.

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.

Step 3: Setting Up Endpoints, Routing, and Middleware Components

app.MapGet(“/”, () => “Hello World!”);:

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.

 () => “Hello World!”: This is an inline lambda function (handler function)


that returns the string “Hello World!”.

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

Step 4: Running the Application

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.

Understanding MapGet Method in ASP.NET Core:


Routing in ASP.NET Core is responsible for matching incoming HTTP requests to
defined endpoints in our application. Endpoints are executable code that runs in
response to a request. The following is the default code for the Main method of
the Program class when we created the ASP.NET Core Empty project.

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.

What is a Web Server?


This is the physical or virtual machine that runs the server software, such as
Apache, Nginx, or Microsoft’s Internet Information Services (IIS), where we host
our application. The web server handles requests from clients (web browsers),
executes the appropriate application logic, and then sends the response back to
the client.

What are Hosting Models in ASP.NET Core?


In ASP.NET Core, a hosting model defines how your application is hosted,
configured, and served to handle incoming HTTP requests. They determine the
relationship between the ASP.NET Core application and the web server,
influencing factors such as performance, scalability, and deployment flexibility.
There are two primary hosting models in ASP.NET Core:
 In-Process Hosting
 Out-Of-Process Hosting
These models determine how the ASP.NET Core application is hosted, which web
servers are used, and how requests are processed.

Example to Understand InProcess Hosting Model in ASP.NET Core


Application.
When we create a new ASP.NET Core Empty application, the ASP.NET Core
framework creates the following Program class with the Main method by default.

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.

Some of the key configurations are:


 Kestrel Configuration: Kestrel is configured as the default web server and
is optimized for serving ASP.NET Core applications.
 IIS Integration: If the application is hosted on Windows, it sets up IIS
integration to ensure compatibility with IIS or IIS Express.
 Environment: It also configures the server’s environment (e.g.,
development, staging, production) and URLs the app will listen on.
 Hosting Model: It also configures whether to use InProcess or Out of
Process hosting models.

How Do We Configure InProcess Hosting in ASP.NET Core?


When we create a new ASP.NET Core Web Application using any project template
in .NET 8, by default, the project is configured to use the InProcess Hosting Model
if the application is intended to be hosted in IIS or IIS Express. The InProcess
Hosting Model performs better than the OutOfProcess Hosting Model because the
ASP.NET Core application runs within the same IIS worker process (w3wp.exe),
which reduces overhead by avoiding cross-process communication.

Method 1: Using Project Properties File


To Manually configure the InProcess Hosting for the ASP.NET Core Web
application, there is only one simple setting: add the <AspNetCoreHostingModel>
element to the application project file with a value of InProcess. To do so, right-
click on your project from the solution explorer and click the Edit Project File
option from the context menu, as shown in the code below.
Once you open the Application Project file, modify it as shown below. As you can
see, we have added the <AspNetCoreHostingModel> element and set its value
to InProcess. The other possible value for this element is OutOfProcess.

What Happens When We Set the Hosting Model as InProcess?

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.

How Do We Use InProcess Hosting Model to Run Applications?


To use the InProcess Hosting Model in Visual Studio, we first need to set the
launch profile to IIS Express, as shown in the image below.

Then, we need to set the AspNetCoreHostingModel element value to InProcess


within the Project Properties file and run the application. You will get the
following output:

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.

What is IIS Express?

IIS Express is a lightweight, self-contained version of Internet Information


Services (IIS) designed for developers to use on their local development
machines. It provides a web server environment that is similar to the full version
of IIS, making it easier to develop and test web applications locally before
deploying them to production servers.

Kestrel Web Server in ASP.NET Core Application


What is Kestrel Web Server?
As we already discussed, ASP.NET Core is a Cross-Platform framework. It
supports developing and running applications on multiple operating systems,
such as Windows, Linux, or MacOS.

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 launchSettings.json file contains configurations for different profiles, which


specify how the application should be launched. Each profile can define settings
such as the environment variables, the server to use (e.g., Kestrel, IIS Express),
the application URL, and more. This allows developers to easily switch between
different launch configurations without modifying the application code.

Key Settings of launchSettings.json file:


The following are some of the key primary settings that we are doing in the
launchSettings.json file:
 Profile Configuration: Define multiple launch profiles for different
scenarios (e.g., running with IIS Express, Kestrel, or using both IIS and
Kestrel).
 Environment Variables: Specifies environment variables that are
available when the application runs (e.g., Development, Staging,
Production),
 Application URLs: Specify the URLs the application will listen on during
development.
 Launch Browser: This setting determines whether a browser should be
automatically launched when the application starts and which URL it
should open.

The launchSettings.json file in an ASP.NET Core project defines various profiles


(such as HTTP, HTTPS, and IIS Express) for running the application in different
environments (like Development, Staging, or Production) with specific
configurations. It allows developers to define settings like the server type,
application URL, environment variables, and more, making it easy to run the
application in different contexts during development.

The launchSettings.json file is located in the Properties folder of the ASP.NET


Core project. It has a JSON structure and contains different profiles, each
specifying how the application can be launched. When we create a new ASP.NET
Core project, we typically find some default settings like the ones below:
Understanding ASP.NET Core LaunchSettings Profiles
Each profile under the “profiles” section provides a different way to launch the
application during development. Profiles can specify settings like the application
URL, environment variables, whether to launch the browser, and more. By
default, it comes with the following three profiles:
HTTP Launch Profile:

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

HTTPS Launch Profile:

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.

Environment Variables: The ASPNETCORE_ENVIRONMENT environment


variable is crucial for running your application in different environments (e.g.,
Development, Staging, Production). Depending on the value of this variable,
different configurations are loaded (such as connection strings, logging settings,
etc.).
ASP.NET Core AppSettings.json File
What are the Different Configuration Sources Available in the ASP.NET Core
application?
If you have worked with earlier versions of ASP.NET, you may be familiar with
the web.config file, which was used to store application configuration settings
such as database connection strings, API keys, logging details, and global
variables.
In ASP.NET Core, we don’t have a web.config file. However, the configuration
settings can be provided through various configuration sources, allowing more
flexibility and better environment management. Some of these configuration
sources are as follows:
 appsettings.json: A JSON file for storing general application settings.
 appsettings.{Environment}.json: Environment-specific JSON files (e.g.,
appsettings.Development.json, appsettings.Production.json, and
appsettings.Staging.json). These override settings in the main
appsettings.json file based on the current environment.
 Environment Variables: Values defined in the environment in which the
application is running, often used in containerized deployments. In Visual
Studio, i.e., in the Development machine, we can achieve the same
using launchsettings.json file.
 User Secrets: Used for storing sensitive information in development (e.g.,
API keys, passwords) without exposing it in source code. It is used during
local development. They are not intended for production use.
 Command-line Arguments: Parameters passed when launching the
application, which can override settings from all other sources.

What is the ASP.NET Core AppSettings.json File?


The appsettings.json file is a JSON configuration file in ASP.NET Core for storing
application-specific settings that can be easily modified without recompiling the
application, making the configuration process more dynamic. It provides a
structured way to define configuration settings such as:

 Database connection strings


 Logging configuration
 API keys
 Authentication settings
 External API URLs
 Application-level global variables
ASP.NET Core supports environment-specific configuration files
(e.g., appsettings.Development.json, appsettings.Staging.json, and
appsettings.Production.json). Depending on the application’s environment,
these files override the base settings in appsettings.json. This allows us to have
different settings for development, staging, and production environments.
When we create an ASP.NET Core Web Application using templates like Empty,
Razor Pages, MVC, or Web API, Visual Studio automatically creates an
appsettings.json file in the project root directory, as shown in the image below.

Understanding the Structure of appsettings.json


If you open the ASP.NET Core appsettings.json file, you will see the following code
by default, which was created by Visual Studio.

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.

ASP.NET Core AppSettings.json File Real-Time Examples


The following are some of the real-time examples of how the appsettings.json file
can be used in ASP.NET Core applications:
Database Connection Strings:
In this example, a connection string is defined for a database. The application can
access this connection string to interact with the database.

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.

Custom Application Settings


Custom settings specific to the application, like page size for pagination or
support email addresses.

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.

Where Do We Use Middleware Components in the ASP.NET Core


Application?
Middleware components are used in an ASP.NET Core application to handle
cross-cutting concerns such as authentication, authorization, logging, error
handling, routing, and other application-level services. Middleware components
are configured in the HTTP request processing pipeline, and they determine how
requests are handled and responses are returned.

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.

UseAuthentication: This middleware adds to the ASP.NET Core pipeline and is


responsible for validating the credentials provided in the request. It
authenticates users and sets the user identity on the request context. This
middleware is typically added after UseRouting but before UseAuthorization.

UseAuthorization: This adds the authorization middleware to the pipeline. It


checks whether an authenticated user has the necessary permissions to access a
given resource or endpoint. This middleware ensures that security policies are
enforced by verifying whether a user is allowed to perform specific actions.
UseHttpsRedirection: Automatically redirects HTTP requests to HTTPS to
ensure that all communication between the client and server is encrypted and
secure. This is crucial for maintaining data integrity and confidentiality.

UseDeveloperExceptionPage: Provides a detailed error page in the browser


during development, including stack traces, query parameters, cookies, and
headers when an exception occurs. This middleware helps developers diagnose
issues during the development phase.

UseExceptionHandler: Handles exceptions that occur during request processing


by catching them and executing custom error-handling logic. It is used in
production environments to manage exceptions, such as by redirecting users to a
custom error page or returning a standard error response.

UseStaticFiles: This middleware enables serving static files like images,


JavaScript, and CSS files directly from the web server to the client. It is essential
for delivering static resources that do not change frequently, enhancing
performance by allowing the server to serve these assets without processing
them through the MVC or Web API pipeline.

The middleware component must be added in the correct sequence to ensure


proper functionality in the application’s request pipeline. The middleware
configuration enables ASP.NET Core applications to perform essential processing
tasks, handle security, and provide a smooth user experience.

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 Do We Configure Middleware Components in ASP.NET Core


Applications?
We need to configure the Middleware Components within the Main() method of
the Program class, which is present inside the Program.cs class file using the
WebApplication instance.
When we create a new ASP.NET Core Empty Web Application, the Program class
is created with the Main method by default, as shown in the image below. The
following Main method configures two middleware
components, MapGet and Run, by default.

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.

We have a Logging Middleware Component. This component logs the request


time and then passes the HTTP Request to the next middleware component, i.e.,
the Static Files Middleware component in the Request Pipeline, for further
processing.
A Middleware Component in an ASP.NET Core Web Application may also handle
the HTTP Request by generating an HTTP Response.

For example, we have a Static Files Middleware Component. Suppose the


incoming HTTP request comes for some static files such as images, CSS files,
JavaScript, etc. In that case, this Static Files Middleware component can handle
the request and then Short-Circuiting the Request Processing Pipeline by not
calling the Next Middleware Component in the pipeline, i.e., the MVC Middleware
Component.
The ASP.NET Core Middleware Components can access both the HTTP Request
and Response in the pipeline. So, a middleware component can also process the
outgoing response. For example, the logging middleware component, in our case,
may log the time when the response is sent back to the client.

What is the Execution Order of Middleware Components?


It is very important to understand the execution order of Middleware
Components in ASP.NET Core Web Applications. These components are executed
in the same order as they are added to the Request Processing Pipeline for
incoming requests and in reverse order for outgoing responses. So, we must take
proper care when adding the Middleware Components to the Request Processing
Pipeline. If we add them in the wrong order, then we might get unexpected
behavior.

How Do We Configure Middleware Components in ASP.NET Core?


To configure Middleware Components, we can use the Map/MapGet, Run, and
Use extension methods in ASP.NET Core applications.

Configuring Middleware Components using Map/MapGet Extension Method:


First, let us see how to configure Middleware Components using
the MapGet Extension method. So, please modify the Main method of the
Program class as follows to add a few Middleware Components using the Map
Extension Method.
Now, run the application and access the endpoints using the appropriate URL.
Based on the URL, the respective endpoint will be executed. Instead of using
MapGet, we can also use the Map extension method, and it should work as
expected.

What is the Difference Between MapGet and Map Extension Methods in


ASP.NET Core?
In ASP.NET Core, both MapGet and Map are extension methods used for defining
endpoint middleware and mapping the incoming HTTP requests to specific
middleware components, but they have distinct purposes and use cases:

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 ASP.NET Core request processing pipeline is a series of middleware


components that handle incoming HTTP requests and responses in an ASP.NET
Core Web application. Each middleware component is responsible for a specific
task, such as authentication, routing, logging, caching, encryption and decryption,
response generation, etc. The pipeline is configured in the Program class of an
ASP.NET Core application.

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.

ExceptionHandler: This middleware is often used to handle exceptions globally.


If an unhandled exception occurs, it handles it, logs it, and returns a proper error
response, usually a custom error page or a JSON error message.

HSTS (HTTP Strict Transport Security): This middleware enforces strict


security policies, telling browsers to only interact with the application over
HTTPS. This means this middleware ensures that the application only serves
content over HTTPS and prevents any HTTP requests by enforcing strict
transport security policies. This middleware is often used in production
environments to enhance security.
HttpsRedirection: This middleware redirects HTTP requests to HTTPS. By
redirecting any HTTP request to HTTPS, this middleware ensures that all traffic is
encrypted for security.

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.

CORS (Cross-Origin Resource Sharing): This middleware handles CORS


policies (cross-origin requests), allowing or denying requests from different
origins. CORS is important for accessing resources from different domains and is
essential for APIs used by frontend applications hosted on different origins.

Authentication: This middleware handles the authentication or identity of the


user or client making the request by validating credentials (e.g., JWT tokens,
cookies, etc.). It ensures that the user is authenticated before reaching certain
parts of the application.

Authorization: This middleware determines whether an authenticated user is


allowed to access a specific resource or endpoint. It checks if the authenticated
user has permission to access the requested resource.

Custom Middlewares (Custom1, Custom…): This represents any custom


middleware components you may have added to the pipeline. These custom
middleware components can perform various operations on the request or
response, such as logging, request modification, caching, modifying headers,
custom validation, etc.

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 second middleware logs the information “Middleware2: Incoming Request”.


As a result, we see this log information after the first log. Then, the second
middleware calls the next(), invoking the third middleware in the request
processing pipeline, Middleware3.

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.

Key Points to Remember:


 The ASP.NET Core Request Processing Pipeline consists of a sequence of
Middleware Components that will be called one after the other.
 Each Middleware Component can perform some operations before and
after invoking the next Middleware Component using the next method. A
middleware component can also decide not to call the next middleware
component, which is called short-circuiting the request pipeline.
 The Middleware Component in ASP.NET Core has access to both the
incoming request and the outgoing response.

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.

Key Characteristics of the wwwroot Folder


 Default Location: The wwwroot folder sits at the root level of an ASP.NET
Core project.
 Direct Access to Files: Files within wwwroot are directly accessible by
clients via relative URLs. For instance, a file named styles.css in
wwwroot/css can be accessed as http://<your-app-url>/css/styles.css.
 Static Files Middleware: To serve files from wwwroot, we must use the
UseStaticFiles middleware in the application’s middleware pipeline.
 Enhanced Security: Files located outside wwwroot aren’t publicly
accessible, which helps safeguard application logic and sensitive files. Only
files within wwwroot or subdirectories are served to clients, enhancing
security by preventing unauthorized access to server code.

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

[1] UseStaticFiles Middleware in ASP.NET Core Web Application:


One of the most important features of almost all web applications should be the
ability to serve static files directly from the file system. Serving these files
efficiently is crucial for improving page load times and user experience. Static
files such as HTML, Images, CSS, and JavaScript are important assets of a Web
Application, and ASP.NET Core can serve these files directly to clients using Static
Files Middleware.

How Do We Configure the Static Files Middleware in ASP.NET Core


Application?
To handle the static resources in the ASP.NET Core Web Application, we need to
configure a middleware called UseStaticFiles() into the application Request
Processing Pipeline.

The UseStaticFiles() middleware is an inbuilt Middleware provided by the


ASP.NET Core Framework to handle the static files in an ASP.NET Core Web
Application.

Let us Modify the Program class, as shown below, to register the UseStaticFiles()
Middleware Component in the application’s Request Processing Pipeline.

How Does UseStaticFiles() Middleware Work Internally?

When a client requests a file, such as /logo.png, here’s how UseStaticFiles()


processes the request:
Request Interception: When the UseStaticFiles() middleware is registered, it
intercepts requests for file paths.
Path Matching: The middleware examines the request path. If the path
corresponds to a file in the static file directory, i.e., wwwroot (or the custom
folder specified with WebRootPath), it prepares the file for delivery.

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.

Skipping Application Logic: By serving static files directly, the middleware


bypasses the rest of the ASP.NET Core pipeline, improving performance by
reducing unnecessary processing for static assets.

Caching and Security: To improve performance and control access, we can


configure caching headers and set security rules for serving static files.

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

[2] UseDefaultFiles middleware Component in ASP.NET Core


The UseDefaultFiles middleware component in ASP.NET Core specifies a default
file (such as index.html or default.html) to be served automatically when a user
navigates to a directory without specifying a specific file name.

For instance, if a user visits the root URL (https://yoursite.com), UseDefaultFiles


will look for specific default files in the wwwroot folder and serve the first one it
finds instead of displaying a directory listing or requiring a full URL path to the
file (e.g., https://yoursite.com/index.html).

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.

[3] UseDirectoryBrowser Middleware Component in ASP.NET Core


Application:
The UseDirectoryBrowser middleware component in ASP.NET Core enables
directory browsing functionality, allowing clients to view the directory’s file
structure.

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.

How Does UseDirectoryBrowser Work Internally?


When a client accesses the specified RequestPath, the middleware:
 Check for the presence of the UseDirectoryBrowser middleware.
 Generates an HTML page showing the files and directories within the
specified folder.
 Lists files with links, allowing users to download or view the files directly.

[4] UseFileServer() Middleware Component in ASP.NET Core:


The UseFileServer middleware component in ASP.NET Core provides an all-in-
one solution for serving static files, setting a default page, and enabling directory
browsing within an ASP.NET Core Web application.

By combining the functionalities of UseStaticFiles, UseDefaultFiles, and


UseDirectoryBrowser, UseFileServer simplifies the configuration process for
serving static content and managing directory browsing. So, when we add
UseFileServer to the middleware pipeline, it automatically includes:
 Static File Serving (UseStaticFiles): This option enables the serving of
static files (e.g., CSS, JavaScript, images) from the wwwroot directory or any
specified directory.
 Default File Serving (UseDefaultFiles): Configures a default file (e.g.,
index.html, default.html) to be displayed when the user accesses the root
URL of a directory.
 Directory Browsing (UseDirectoryBrowser): Enables the option for
users to view the directory contents in the browser (e.g., see the files in a
folder if no default file is present).

How to Use UseFileServer in ASP.NET Core


Using UseFileServer is straightforward. We need to use
the app.UseFileServer(); middleware. This single line configures all three
functionalities to serve static files, set a default page, and enable directory
browsing.

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

In ASP.NET Core, the middleware components UseDirectoryBrowser,


UseStaticFiles, UseFileServer, and UseDefaultFiles serve different purposes when
handling static content. Each enables specific functionality, and understanding
their differences helps correctly configure how static files and directories are
accessed.

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

Configures a default file to be served automatically when a directory is requested


(e.g., index.html or default.html). By default, look for index.html, index.htm,
default.html, or default.htm by default. It only sets the default file behavior and
does not serve the files itself; it requires UseStaticFiles afterward to serve the
files.

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.

Use UseDirectoryBrowser in scenarios where directory contents need to be


accessible, such as in a development environment or an internal documentation
site.

UseFileServer

It combines the functionality of UseStaticFiles, UseDefaultFiles, and


UseDirectoryBrowser into a single middleware. This is useful for scenarios where
you need to enable multiple static file-related features at once.
Use UseFileServer when you want a single middleware configuration to serve
static files, handle default files, and enable directory browsing.

You might also like