Select Page

ASP.NET Core Hosting on IIS on Windows

This article will provide details about how to deploy ASP.NET Core web application or Web API on IIS. .NET Core 2.2 onwards there were significant changes in the hosting model to IIS. Prior to .NET Core 2.2 only option available was to use IIS as a reverse proxy to ASP.NET Core Kestrel web server.

With .NET Core 2.2 option was added for direct in-process hosting to IIS which can improve the performance significantly. The old approach with IIS as a reverse proxy is also available as an out-of-process hosting model. ASP.NET Core hosting on IIS supports two models for hosting on the IIS i.e. In-process hosting model & out-of-process hosting model.

ASP.NET Core Hosting on IIS is different as compared to ASP.NET Webforms or ASP.NET MVC.

Supported operating systems

  • Windows 7 or later
  • Windows server 2012 R2 or later

Apps published for 32 bit (x86) and 64 bit (x64) are supported. Application pools under should be configured accordingly for 32-bit & 64-bit apps.

Type of Hosting Models

ASP.NET Core Hosting on IIS
In-process hosting model

As the name suggests ASP.NET Core application runs in the same process as IIS (w3wp.exe) and it does not use the Kestrel web server. This hosting model uses IISHttpServer that is hosted directly inside the application pool. This hosting model provides a significant performance improvement over the other out-of-process model as it does not have to forward requests to Kestrel for processing. IIS handles process management in the traditional way with the help of windows process activation service (WAS).

Request flow details:

  • Request arrives from web at HTTP.sys
  • HTTP.sys routes the request to IIS
  • ASP.NET Core module receives the request and passes it to IIS HTTP Server.
  • IISHTTPServer passes the request to ASP.NET Core middleware pipeline.
  • ASP.NET Core application handles the request and returns response
Out-of-process hosting model

Again as the name suggests here ASP.NET Core application runs in a separate process from the IIS worker process. This is similar to what was available in ASP.NET Core versions prior to 2.2. ASP.NET Core module handles process management, this module is responsible for starting the ASP.NET Core App when the first request arrives & also restarts if it shuts down or crashes.

Here IIS acts as a reverse proxy to Kestrel web server where ASP.NET Core application is running. For application to be configured as an out-of-process model it needs to specify UseIISIntegration as part of WebHostBuilder code in the program.cs file. ASP.NET Core module doesn’t support HTTPS forwarding.

Steps for ASP.NET Core hosting on IIS

  • Publish your application
  • Install/Enable IIS Server on windows
  • Install the .NET Core Hosting Bundle
  • Create a new application pool & website for your application
Publish your Application

Right click on project in Solution Explorer and select Publish option. This should being up the screen to publish your code. Select Folder option to publish all the files to a folder. This folder will be configured in IIS as website folder.

IIS Configuration

Use the Add Roles & Features wizard to Enable IIS on Windows server operating system.

IIS Installation

Select following services under web server on Select role services screen

IIS Installation Select Services

For windows desktop operating system select Control Panel ==> Program ==> Program & Features ==> Turn windows features on or off and select following features for installations

IIS Installation on Windows Desktop

Newsletter Subscription

Stay updated! Instantly get notified about my new articles in your mailbox by subscribing via email

Install .NET Hosting Bundle

You can download the required version of the hosting bundle from here. The hosting bundle installs the .NET Core Runtime, .NET Core Library, and the ASP.NET Core Module.

If the Hosting Bundle is installed before IIS, the bundle installation must be repaired. Run the Hosting Bundle installer again after installing IIS.

Create IIS Site

Open IIS Manager & expand server node in connections panel on left hand side. Right click site folder and select “Add Website…” from the context menu. Provide Site name, Physical path (where code was published), binding configuration details & click on ok.

IIS Create Website

Finally browse and check your website.

Summary

ASP.NET Core hosting on IIS supports two models for hosting on the IIS i.e. In-process hosting model & out-of-process hosting model. .NET Core 2.2 onward there were significant changes in the hosting model to IIS.

In-process hosting model provides a significant performance improvement over the other out-of-process model as it does not have to forward requests to Kestrel for processing

References: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1

You can also check my other Article on Configuring multiple ASP.NET Core hosting environment: https://procodeguide.com/programming/asp-net-core-hosting-environment/

Configuring multiple ASP.NET Core hosting environment

The hosting environment is used to indicate at runtime on which environment an ASP.NET Core application is running. There can be multiple values for ASP.NET Core Hosting Environment and it can be set any single value. Framework provided environments are Development, Staging & Production but you can specify your own values as well i.e. Testing, QA, PrePROD, etc.

Environment variables allow the application to be configured as per the environment on which the application is running.

Why hosting environments?

As part of the software development life cycle, an application has to go through various phases like Development, Testing & Production. We as application developers need to configurable different parameters for different environments like each environment will have its own database, different versions (URL) of third party services, different application features like logging, bundling, minification, exception handling, etc based on the environment on which application is running.

Multiple environments let us control these parameters at runtime i.e database connections, third party service URLs, application behavior like logging, exception, bundling, etc can be configured environment wise.

How to set ASP.NET Core hosting environment

There are a number of ways to set the hosting environment variable. This environment variable needs to be set on each machine on which the application is required to run.

using windows command line

To set the environment variable from command prompt following command can be used. This is applicable for the current session and app should be started using dotnet run command.

set ASPNETCORE_ENVIRONMENT=Staging
dotnet run --no-launch-profile
using PowerShell
$Env:ASPNETCORE_ENVIRONMENT = "Staging"
dotnet run --no-launch-profile

Both command line & PowerShell sets environment variables only for the processes launched from that command window.

using windows environment variables

To set ASP.NET Core hosting environment variable globally in windows so that each you don’t need to set it before running the application use windows environment variables

To set environment variable globally open Control Panel ==> System ==> Advanced System Settings ==> Environment Variables ==> System Variable New/Edit & set values in ‘name’ and ‘value’ and click ok

ASP.NET Core Hosting Environment
using web.config

Environment variable can be set in web.config as well. Environment variable can be specified for the process in the processPath attribute in web.config. Environment variables set in this section takes precedence over system environment variables.

<aspNetCore processPath="dotnet"
      arguments=".\MyApp.dll"
      stdoutLogEnabled="false"
      stdoutLogFile=".\logs\stdout"
      hostingModel="inprocess">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
  </environmentVariables>
</aspNetCore>

Developers can use this to temporarily set the environment to development for debugging purpose.

using Per IIS Application Pool

Environment variable can also be set at IIS pool level for an application running in an isolated application pool. When ASPNETCORE_ENVIRONMENT is set for an app pool, its value overrides a setting at the system level.

<applicationPools>
   <add name="CorePool" managedRuntimeVersion="v4.0" managedPipelineMode="Classic">
      <environmentVariables>
         <add name="ASPNETCORE_ENVIRONMENT" value="Staging" />
      </environmentVariables>
   </add>
</applicationPools>

AppCmd.exe can be used to add environment variables to the IIS pool level.

appcmd.exe set config -section:system.applicationHost/applicationPools /+"[name='CorePool'].environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging']" /commit:apphost

Restart IIS or Server after setting the environment variable in IIS for application to have new values available after changes.

How to use ASP.NET Core hosting environment in your application

Environment based startup class

Below is the example of environment based startup class in which IWebHostingEnvironment has been injected to identify the environment and add code behavior accordingly.

public class Startup
{
    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        Configuration = configuration;

        var builder = new ConfigurationBuilder()
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
    }

    //Remaining code was removed

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

        app.UseRouting();

        //Remaining code was removed
    }
}

In the above code in startup constructor environment variable name has been used to load appsettings.json file based on the environment configured for application i.e. appsettings.development.json or appsettings.production.json file will be used based on the environment set at runtime.

Also in the configure method different application behavior has been set for exception handling based on the environment set at runtime.

Newsletter Subscription

Stay updated! Instantly get notified about my new articles in your mailbox by subscribing via email

How to add custom ASP.NET Core hosting environment

Development, Staging & Production environments are provided by default by the framework. But ASPNETCORE_ENVIRONMENT can be set to any string value. To configure your own environments following extension class can be added.

public static class HostingEnvironmentExtensions
{
    public const string QAEnvironment = "QA";
    public const string UATEnvironment = "UAT";
    public const string TestEnvironment = "Test";

    public static bool IsQA(this IWebHostEnvironment hostingEnvironment)
    {
        return hostingEnvironment.IsEnvironment(QAEnvironment);
    }

    public static bool IsUAT(this IWebHostEnvironment hostingEnvironment)
    {
        return hostingEnvironment.IsEnvironment(UATEnvironment);
    }

    public static bool IsTest(this IWebHostEnvironment hostingEnvironment)
    {
        return hostingEnvironment.IsEnvironment(TestEnvironment);
    }
}

Once configured it will be available under environment variable as shown below

ASP.NET Core Custom Environments

Summary

ASP.NET Core hosting environment allows developers to control how their application will behave in different environments. There are multiple ways available to set an environment variable for the application.

ASP.NET Core hosting has provided 3 environments i.e. development, staging & production by default but custom environments can be added and practically any string can be used for environment name.

References: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-3.1

You can also check my other Article on ASP.NET Core bundling & minification: https://procodeguide.com/programming/asp-net-core-bundling-minification/