0% found this document useful (0 votes)
16 views

Core 1

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Core 1

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Creating ASP.

NET Core Web Application using Visual Studio

Here I will discuss How to Create the ASP.NET Core Web Application using Visual Studio 2022 and .NET 8.

Creating the First ASP.NET Core Web Application using Visual Studio 2022 and .NET 8

In this demo, 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.

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.

1
Once you click on the Next button, the Additional Information window will open. 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.

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.

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.

2
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 it will change the output accordingly.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Welcome to .NET 6");
app.Run();
}
}
}
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.

3
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

4
 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.
Note: In our coming articles, we will discuss in detail how and when to use some of the above project templates.

ASP.NET Core Project File

In this article, I will discuss the ASP.NET Core Project File in detail. Please read our previous article, where we
discussed How to Create the ASP.NET Core Web Application using Visual Studio 2022 and .NET 8 and the
different project templates available as part of the ASP.NET Core Web Application.

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 we use C# as the programming language, it will create
the project file with the “.csproj” extension. Similarly, if we 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 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.

5
Once you click on the Edit Project File then the Project file will open in the Visual Studio editor as shown in the
below image.

Understanding the ASP.NET Core Project File:

<Project Sdk=”Microsoft.NET.Sdk.Web”>

This element defines the project and specifies that it uses the Microsoft.NET.Sdk.Web SDK, which is used for
building web applications, including ASP.NET Core applications. The SDK includes the necessary tools and libraries
for web development.

<PropertyGroup>

The <PropertyGroup> element is used to define a group of properties that control various settings and
configurations for the project. This specific PropertyGroup contains three properties:

 <TargetFramework>net8.0</TargetFramework>: This property specifies the target framework for the


project. net8.0 indicates that the project is targeting .NET 8.0. This setting determines which version of
the .NET runtime and libraries will be used.

6
 <Nullable>enable</Nullable>: This property enables nullable reference types for the project. When this
is set to enable, the compiler will enforce nullable reference type annotations and warnings, helping to
avoid null reference exceptions by making the developer explicitly declare whether a reference type can
be null. The value for this element is enable and disable.
 <ImplicitUsings>enable</ImplicitUsings>: This property enables implicit using directives. When set to
enable, the compiler automatically includes commonly used namespaces in the global scope, reducing
the need to add using directives manually at the top of each file. The value for this element is enable and
disable.
Adding Packages in ASP.NET Core:

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

The package reference is added to the application project file whenever we add new packages to our application.
Please have a look at the following Dependencies section of our project. Whenever we add a package, that
package and its dependency packages are stored here.

Let’s first add a package from the NuGet Package Manager and see what happens. 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.

7
Once the package is installed successfully, it will add a reference 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
other files 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 for serializing and deserializing JSON data. By including
this package reference, the project can use the functionality provided by Newtonsoft.Json.
Note: Deleting that package will delete the reference from both the Package Dependencies and the project file.

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

What are the settings we can do in ASP.NET Core Project files?

ASP.NET Core Project file (.csproj) allows us to configure a variety of settings that control how our application is
built, run, and deployed. These settings are defined using XML elements within the project file. The following are
some of the most common settings we can configure in an ASP.NET Core project file:

 SDK Type: <Project Sdk=”…”>: Specifies the SDK used, which defines the tools and libraries included.
Common SDKs for ASP.NET Core include Microsoft.NET.Sdk.Web for web apps and Microsoft.NET.Sdk for
other types of apps.
 Target Framework: <TargetFramework> or <TargetFrameworks>: Sets the version of .NET that the
project targets.
 Nullable Reference Types: <Nullable>: Enables or disables nullable reference types, which can help
prevent null reference exceptions.
 Implicit Usings: <ImplicitUsings>: Automatically includes a set of common using directives to reduce
boilerplate code.
 Output Type: <OutputType>: Determines the output of the project (e.g., Exe for executable, Library for
DLL).
 Package References: <PackageReference Include=”PackageName” Version=”VersionNumber” />:
Defines NuGet package dependencies for the project.
 Assembly Information: <AssemblyName>, <RootNamespace>: Customizes the output assembly’s name
and the default namespace.
 Build Configurations: <PropertyGroup Condition=”…”>: Allows for defining different settings for different
build configurations, like Debug or Release.
 Language Version: <LangVersion>: Specifies the C# language version to use.
For example:

<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<OutputType>Exe</OutputType>
<AssemblyName>FirstCoreWebApp</AssemblyName>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>10.0</LangVersion>
</PropertyGroup>

9
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<Optimize>true</Optimize>
<WarningsAsErrors>true</WarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>
Understanding Condition=”‘$(Configuration)’ == ‘Release'”:

The Condition attribute on the <PropertyGroup> element allows us to specify when the properties inside this
group should be applied. The condition is written as an expression that evaluates to true or false.

“‘$(Configuration)’ == ‘Release'”: This condition checks if the build configuration is set to Release. The $
(Configuration) is a variable that represents the current configuration used during the build process (common
values are Debug and Release). If the condition evaluates to true (i.e., the build is a Release build), then the
properties inside this group are applied. Properties within the <PropertyGroup> are as follows:

 <Optimize>true</Optimize>: This property enables the compiler’s optimization features for the project
when building in Release mode. Optimization improves the performance of the resulting executable by
rearranging code, removing unnecessary instructions, and performing other efficiency enhancements.
However, it can make debugging more difficult, which is why it’s typically enabled only for Release
builds.
 <WarningsAsErrors>true</WarningsAsErrors>: This property converts all compiler warnings into errors
for the Release configuration. Treating warnings as errors forces the developer to address potential
issues in the code before the build can succeed. This is a useful feature for maintaining code quality,
ensuring that no overlooked warnings result in runtime issues, especially in production environments.
In the next article, I will discuss the ASP.NET Core Main Method in detail. In this article, I will try to explain the
ASP.NET Core Project File in detail. I hope you enjoy this article, and I would like your feedback. Please post your
feedback, questions, or comments about this ASP.NET Core Project File article.

ASP.NET Core Main Method

Here I will discuss the ASP.NET Core Main Method with Examples.

ASP.NET Core Program Class

The Program class in ASP.NET Core contains the Main method and is used to configure and launch the
application. It includes the following:

 Host Configuration: This sets up the application’s fundamental components, such as the web server,
middleware, and services.
 Environment Configuration: The developer can configure different environments (like Development,
Staging, and Production).
ASP.NET Core Main Method

It is similar to the main method used in console or desktop applications. This method is found in the Program.cs
class file and is responsible for bootstrapping the application. The Main method in ASP.NET Core serves as the
entry point for the application. It’s where the application starts running.

 Creating the Host: The Main method is responsible for configuring and building the web host, which will
encapsulate all of the application’s resources, such as dependency injection, logging, and configuration
settings.

10
 Registering the Services: It also configures and registers the services required by the application, such as
MVC, Web API, Razor Pages, etc.
 Register Middleware Components: The Main is also responsible for configuring the Application Request
Processing Pipeline using Middleware Components such as Authentication, Authorization, Routing, etc.
 Running the Application: After building the host and configuring the Request Processing Pipeline, the
Main method calls the Run middleware component, which starts the web server and begins listening to
incoming HTTP requests.
Understanding Program.cs Class File in ASP.NET Core

Open the Program.cs class file, and you will see the following lines. The Main Method of the Program class
contains four lines of code when we created the project with the ASP.NET Core Empty template. This contains all
the initialization code required to create a web server, host the application, and start listening for HTTP requests.

While creating the Project, if you uncheck the do not use top-level statements checkbox, you will not find the
class name and Main method name. This feature was introduced in C# 9, where we do not have to specify the
Program class name and Main method name. This feature allows us to create one top-level file containing only
statements. That top-level file will become the entry point of your application.

It creates the web application in three stages: Create, Build, and Run, as shown in the image below.

Note: The earlier versions of ASP.NET Core created two files: Program.cs and Startup.cs. The Program.cs is
responsible for configuring the host, and the Startup class is responsible for configuring the Services and
Middleware. From .NET 6, both are merged into a Program.cs class file. Let us understand the Program file code
in detail.

Step 1: Creating the Web Host and Services

var builder = WebApplication.CreateBuilder(args);

11
The first line of the code in the Main method creates an instance of the WebApplicationBuilder sealed class. The
CreateBuilder is a static method of the WebApplication class that accepts the Command line arguments as an
input parameter to configure the web host. This statement initializes a builder for the web application with
preconfigured defaults, such as.

1. Set up Web Server (IIS, Kestrel)


2. Host the Application (InProcess or OutOfProcess)
3. Logging (Built-in Service => Debug and Console)
4. Configuration (How to access the Data from Configuration Files)
5. Dependency Injection Container (IServiceCollection where you can register the built-in and custom
services)
6. Adds Framework Provided Services
We then call the Build method using the WebApplicationBuilder instance. As we progress in this course, we will
see how to configure different types of built-in services, such as MVC, Web API, Razor Page, etc. We will also
discuss how to create and configure Custom Services.

Step 2: Building the Application

var app = builder.Build();

The Build method of the WebApplicationBuilder class creates a new instance of the WebApplication class. This
statement converts the configurations set up in the builder into an executable application instance. At this point,
the application is ready to set up endpoints and start handling requests, but it isn’t running yet.

Step 3: Mapping Endpoints

We then use the Web Application instance to set up the Middlewares for our ASP.NET Core Application. The
template has set one middleware component using the MapGet extension method as follows:

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

This line maps HTTP GET requests to the root URL (“/”) to a specific request delegate. Here, the delegate is a
simple lambda function that returns the string “Hello World!”. This means that when a user accesses the base
URL, they receive “Hello World!” as the response.

Step 4: Running the Application

app.Run();

The WebApplication instance’s Run method starts the application. It listens for incoming HTTP requests on the
configured ports and begins processing them according to the defined routes and endpoints.

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. As we progress in this
course, we will discuss How to configure built-in and custom services and middleware components in the .NET 8
Application in detail.

Understanding MapGet Method in ASP.NET Core:

Routing in ASP.NET Core is responsible for matching incoming HTTP Requests (URLs) and navigating those HTTP
requests to the application’s executable endpoints, which will handle the request. Endpoints are nothing but the
application’s executable code that will execute to Handle the Requests. The following is the default code for the
Main method of the Program class when we created the ASP.NET Core Empty project.

12
namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
//Configuring Web Host and Services
var builder = WebApplication.CreateBuilder(args);
//Building the Application
var app = builder.Build();
//Mapping Endpoints
app.MapGet("/", () => "Hello World!");
//Running the Application
app.Run();
}
}
}
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 that it is a GET request, open the browser developer tool by pressing the F12 key, go to the Network
tab, and refresh the page again. 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.

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

Why We Have the Main Method in ASP.NET Core Web Application

Despite ASP.NET Core being focused on web applications, it still uses the Main method because:

 It aligns with the standard .NET application model, making it easier for developers to transition between
different types of .NET applications.
 Having a Main method gives developers explicit control over how the application starts, configures
services, and handles different environments. This is important for more complex applications that
require advanced configurations.
 The Main method is essential for managing the application’s lifecycle. It controls when the application
starts and stops, which is important for managing resources effectively.
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.

In the next article, I will discuss the ASP.NET Core InProcess Hosting Model with Examples. In this article, I will try
to explain the ASP.NET Core Main Method with Examples. I hope this article will help you understand the
ASP.NET Core Main Method in .NET Applications.

ASP.NET Core InProcess Hosting Model

Here I will discuss the ASP.NET Core InProcess Hosting Model with Examples.

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. The following are the Key Concepts of
Hosting:

14
 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). The web server handles requests from clients (web
browsers), executes the appropriate application logic, and then sends the response back to the client.
 Storage: Hosting services provide disk space on a server where your web application’s files and data are
stored. This includes your application code, databases, multimedia files, and other data.
 Database Server: Many web applications require a database to store data. Hosting environments often
include database services like MySQL, PostgreSQL, SQL Server, or MongoDB, which are accessible to your
application for storing and retrieving data.
 Network Connectivity: A host ensures that the server is always connected to the internet with sufficient
bandwidth to handle incoming requests from users.
 Environment Setup: Hosting involves setting up and configuring the software environment needed to
run your application. This can include installing frameworks and libraries and managing settings for
security, traffic handling, etc.
Types of Hosting:

 Shared Hosting: Multiple websites are hosted on the same server, sharing resources (CPU, RAM, disk
space). This is a cost-effective option for smaller websites but may have limitations in performance and
customization.
 VPS (Virtual Private Server) Hosting: A single physical server is partitioned into multiple virtual servers,
each acting as an independent server. This type of hosting offers better performance and customization
compared to shared hosting and is suitable for applications that need more resources and better control.
 Dedicated Hosting: A dedicated server for hosting your web application. This provides full control over
the server and is suitable for high-traffic sites, but it is more expensive than Shared Hosting and VPS.
 Cloud Hosting: Flexible hosting on cloud infrastructure, allowing resources to scale up or down as
needed. AWS, Azure, and Google Cloud provide powerful and scalable hosting solutions. It is cost-
effective as you pay for what you use.
What are Hosting Models in ASP.NET Core?

A hosting model in ASP.NET Core defines the environment and method by which the ASP.NET Core application
runs. It essentially determines how requests are handled and how the application interacts with the web server.
In ASP.NET Core, the hosting model defines how the application starts, how the requests are processed, and how
the responses are returned to clients. ASP.NET Core supports two types of Hosting
Models: InProcess and OutOfProcess. In this article, I will discuss the InProcess Hosting Model in detail, and in
our upcoming article, we will discuss the OutOfProcess Hosting Model.

What is the InProcess Hosting Model in ASP.NET Core?

In this model, the ASP.NET Core Web Application runs in the same worker process as its web server. When using
IIS (Internet Information Services) as the web server with the InProcess Hosting Model, the ASP.NET Core
application runs inside the IIS worker process (w3wp.exe or iisexpress.exe).

This model is known for providing better performance and is generally recommended for applications hosted on
IIS in Windows Server. In InProcess hosting, the ASP.NET Core application runs as part of the IIS worker process.
The application code and the IIS worker process share the same memory space, eliminating communication
overhead between the web server and the application process.

How Does the InProcess Hosting Model Work in ASP.NET Core?

When a request comes to IIS, it is directly processed by the ASP.NET Core application in the same process. Please
look at the following diagram to better understand how the InProcess Hosting Model works. Here, we only use
one server, IIS, to handle client requests and execute the application code.

15
The InProcess Hosting Model works as follows:

Step 1: Request Initiation

The client (such as a web browser or an API consumer) sends an HTTP request (HTTP GET or POST, etc.) to the
ASP.NET Core application. This request is directed to the IIS web server where the application is hosted.

Step 2: Handling by IIS and ANCM

Internet Information Services (IIS) receives the HTTP request. IIS acts as the main entry point for all incoming
client requests. The ASP.NET Core Module (ANCM) plays an important role within IIS. ANCM is responsible for
forwarding the request to the appropriate IIS worker process when the application is configured for In-Process
hosting. The IIS worker process is where the ASP.NET Core application runs. ANCM loads the .NET Core runtime
and the ASP.NET Core application into this process.

Step 3: IIS HTTP Server Handles the Request

Once the request is within the IIS worker process, the IIS HTTP Server (which is part of the ASP.NET Core) handles
it. The IIS HTTP Server is a part of the in-process hosting model that enables the integration of ASP.NET Core
with IIS.

Step 4: Request Processing

The IIS HTTP Server receives the request from ANCM and passes it through the ASP.NET Core middleware
pipeline. This middleware pipeline is where most of the application code (your Application Code) is executed,
including routing, controllers, and response generation. Middleware components in ASP.NET Core handle
different key functionalities of the request (authentication, logging, error handling, etc.) and pass the request
down the pipeline until it reaches the endpoint that generates a response.

Step 5: Response Generation

The application generates a response based on the processed request. This might involve rendering a view,
returning a JSON object, or other content types. The response then travels back through the middleware
pipeline, allowing any response-modifying middleware (such as adding response headers, modifying the content,
logging the response, encryption the response, etc.) to act on it.

Step 6: Response Sent to Client

Once the response is finalized, it is sent from the application code back to the IIS HTTP Server within the worker
process. ANCM ensures that the response generated by the application is correctly formatted and ready to be
sent back to the client. IIS receives the response from ANCM and forwards it to the client using the HTTP
protocol.

Step 7: Client Receives the Response

16
The client (e.g., web browser or an API consumer) receives the HTTP response (e.g., HTML, JSON, etc.) sent by IIS,
renders the content, and displays it to the user.

What is the ASP.NET Core Module?

The ASP.NET Core Module (ANCM) is a native IIS module that allows you to host ASP.NET Core applications. It
acts as a bridge between the IIS web server and the ASP.NET Core application. It is responsible for forwarding
requests to the application. ANCM ensures that the app starts when needed and handles requests appropriately
according to its hosting model.

What is an IIS HTTP Server?

The IIS HTTP Server (IISHttpServer) is a component within the ASP.NET Core in-process hosting model that
integrates with IIS. It handles HTTP requests and responses within the IIS worker process when the application is
hosted in-process. It’s part of the ASP.NET Core framework and handles the request-processing pipeline within
the IIS process.

What is IIS?

Internet Information Services (IIS) is a flexible, secure, general-purpose web server from Microsoft that is used to
host websites and web applications on the Windows platform. It supports HTTP, HTTPS, FTP, FTPS, and SMTP. IIS
is widely used in Windows environments to serve web content and manage web applications, providing features
like security, performance, etc., and integrates with ASP.NET Core through the ASP.NET Core Module.

What is the IIS Worker Process?

The IIS Worker Process (w3wp.exe) runs web applications hosted on IIS. It executes the application code and
handles web requests and responses. In the in-process hosting model, the ASP.NET Core application runs inside
this process.

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, by default, creates the
following Program class with the Main method.

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 the Web Host, which will host our application using default preconfigured
configurations. The CreateBuilder() method does several things as part of setting the Web host. Some of them
are as follows:

17
 Initialize Host Configuration: It loads configuration settings from various sources, such as environment
variables, command-line arguments, and configuration files (e.g., appsettings.json, launchsettings.json,
etc.) and sets up default configuration providers.
 Set Up Dependency Injection: Initializes the service collection (IServiceCollection) and adds default
services required by the framework. Registers services specified by the application.
 Configure Logging: Sets up default logging providers, such as console and debug logging. Configures
logging based on configuration settings.
 Configure the Web Host: It configures the web host with default configurations. It configures Kestrel as
the web server and sets up IIS integration if it is running on Windows.
 Set Up Middleware Pipeline: Prepares the application to add middleware components that handle HTTP
requests.
Let us understand what exactly the CreateBuilder() method does to configure and set up the Web Host. From a
hosting point of view, an ASP.NET Core Web application can be hosted in two ways: in-Process Hosting or out-of-
Process Hosting. Let us first discuss the in-Process Hosting Model, and then we will discuss the out-of-Process
Hosting Model.

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, the project is
created with InProcess Hosting, which is used for hosting the application in IIS or IIS Express because it gives
better performance than the out-of-process hosting model.

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 then click on 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.

<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>

18
<ImplicitUsings>enable</ImplicitUsings>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
</Project>
Method 2: Specify the Hosting Model as InProcess using GUI

To do so, right-click on your project in the Solution Explorer and click on the Properties option from the context
menu, which will open the Project Properties window. Select the Debug tab from this window and click the Open
debug launch profiles UI button, as shown in the image below.

Once you click on the Open debug launch profiles UI button, the Launch Profile window will open. From this
window, select IIS Express and scroll down. Somewhere, you will find the Hosting Model drop-down list with the
following values. As we have already set InProcess as our hosting model in the Project Properties window, you
will see that the In-Process Hosting Model has been selected as the default hosting model here. Whatever
hosting model you want to use, you can also change it here.

What Happens When We Set the Hosting Model as InProcess?

When we configure the hosting model as InProcess and run 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 performance-sensitive environments.

The process name that will be used to execute the application is w3wp in the case of IIS. Similarly, if it is IIS
Express, the process name will be iisexpress.

19
How Do We Use InProcess Hosting Model to Run Applications?

In order 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 process name in browser you need to


use System.Diagnostics.Process.GetCurrentProcess().ProcessName within the Main method of the Program
class. So, modify the Main method of the Program class as follows.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{

20
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Worker Process Name : " +
System.Diagnostics.Process.GetCurrentProcess().ProcessName);
app.Run();
}
}
}
Now, when we run the application from Visual Studio, it should display the message in the browser, as shown
below. This is because, by default, Visual Studio uses IISExpress when we run an application.

You can also verify whether it is using a Microsoft IIS server by using the browser developer tool. Run the
application and open the browser developer tool by pressing the F12 key. Then, go to the Network tab and issue
the same request again. You will see that it is showing Microsoft IIS as the server in the Response headers, as
shown in the image below.

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.

21
The most important point you must remember is that we use IIS Express only in development, not production.
We need to use IIS in production. In our upcoming session, we will discuss how to deploy an ASP.NET Core
Application on IIS.

Why Does InProcess Hosting Give Better Performance than the OutOfProcess Hosting Model?

In the case of OutOfProcess Hosting, there are 2 Web Servers

1. An Internal Web Server (Kestrel ) and


2. One External Web Server (IIS, Nginx, or Apache).
The internal Web Server is called Kestrel, and the external web server can be IIS, Nginx, or Apache. With the
InProcess Hosting Model, there is only one web server: IIS. So, in the case of the InProcess Hosting Model, we do
not have a performance penalty for navigating the requests between the internal and external web servers. This
is the reason why the InProcess hosting model delivers significantly higher request throughput than the
OutOfProcess hosting model.

When to Use In-Process Hosting Model?

 High-Performance Requirements: The In-Process Hosting Model is often the better choice if your
application demands high performance. It eliminates the overhead associated with inter-process
communication (IPC) that occurs in the OutOfProcess model, thereby reducing response times and
increasing throughput.
 Windows and IIS Environment: InProcess hosting is specifically designed for integration with IIS. If your
production environment uses Windows Server and IIS, the InProcess model can maximize IIS’s native
capabilities and performance optimizations.
 Legacy Integration: If your application relies on IIS-specific features or needs to integrate closely with
legacy systems configured around IIS, the InProcess model offers better integration. It uses full-fledged
IIS features such as advanced configuration, security management, and lifecycle control.
 Development and Testing: The InProcess model offers a straightforward setup that closely mirrors the
IIS production environment for local development and testing, especially when using Visual Studio. This
can help in catching environment-specific issues early in the development cycle.
Next=> So, before understanding the Out-of-Process Hosting Model to host our ASP.NET Core Web Application,
we first need to understand what the Kestrel Web Server is and How It works. Then, we will discuss the Out-Of-
Process Hosting Model.

22

You might also like