www.infoworld.com Open in urlscan Pro
151.101.130.165  Public Scan

URL: https://www.infoworld.com/article/3646098/demystifying-the-program-and-startup-classes-in-aspnet-core.html
Submission Tags: falconsandbox
Submission: On September 27 via api from US — Scanned from DE

Form analysis 1 forms found in the DOM

<form class="gsc-search-box gsc-search-box-tools" accept-charset="utf-8">
  <table cellspacing="0" cellpadding="0" role="presentation" class="gsc-search-box">
    <tbody>
      <tr>
        <td class="gsc-input">
          <div class="gsc-input-box" id="gsc-iw-id1">
            <table cellspacing="0" cellpadding="0" role="presentation" id="gs_id50" class="gstl_50 gsc-input" style="width: 100%; padding: 0px;">
              <tbody>
                <tr>
                  <td id="gs_tti50" class="gsib_a"><input autocomplete="off" type="text" size="10" class="gsc-input" name="search" title="search" aria-label="search" id="gsc-i-id1" dir="ltr" spellcheck="false" placeholder="Start Searching"
                      style="width: 100%; padding: 0px; border: none; margin: 0px; height: auto; outline: none;"></td>
                  <td class="gsib_b">
                    <div class="gsst_b" id="gs_st50" dir="ltr"><a class="gsst_a" href="javascript:void(0)" title="Clear search box" role="button" style="display: none;"><span class="gscb_a" id="gs_cb50" aria-hidden="true">×</span></a></div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </td>
        <td class="gsc-search-button"><button class="gsc-search-button gsc-search-button-v2"><svg width="13" height="13" viewBox="0 0 13 13">
              <title>search</title>
              <path
                d="m4.8495 7.8226c0.82666 0 1.5262-0.29146 2.0985-0.87438 0.57232-0.58292 0.86378-1.2877 0.87438-2.1144 0.010599-0.82666-0.28086-1.5262-0.87438-2.0985-0.59352-0.57232-1.293-0.86378-2.0985-0.87438-0.8055-0.010599-1.5103 0.28086-2.1144 0.87438-0.60414 0.59352-0.8956 1.293-0.87438 2.0985 0.021197 0.8055 0.31266 1.5103 0.87438 2.1144 0.56172 0.60414 1.2665 0.8956 2.1144 0.87438zm4.4695 0.2115 3.681 3.6819-1.259 1.284-3.6817-3.7 0.0019784-0.69479-0.090043-0.098846c-0.87973 0.76087-1.92 1.1413-3.1207 1.1413-1.3553 0-2.5025-0.46363-3.4417-1.3909s-1.4088-2.0686-1.4088-3.4239c0-1.3553 0.4696-2.4966 1.4088-3.4239 0.9392-0.92727 2.0864-1.3969 3.4417-1.4088 1.3553-0.011889 2.4906 0.45771 3.406 1.4088 0.9154 0.95107 1.379 2.0924 1.3909 3.4239 0 1.2126-0.38043 2.2588-1.1413 3.1385l0.098834 0.090049z">
              </path>
            </svg></button></td>
        <td class="gsc-clear-button">
          <div class="gsc-clear-button" title="clear results">&nbsp;</div>
        </td>
      </tr>
    </tbody>
  </table>
</form>

Text Content

Close Ad


infoworld
UNITED STATES
 * United States
 * United Kingdom

 * Software Development
 * Cloud Computing
 * Machine Learning
 * Analytics
 * IDG TECH(Talk) Community
 * Newsletters
 * White Papers/Webcasts

Welcome! Here are the latest Insider stories.
 * How to evaluate software asset management tools
 * How to choose the right data visualization tools for your apps
 * What’s new in Kubernetes 1.22
 * Rust tutorial: Get started with the Rust language

More Insider Sign Out
Sign In Register
×

search
 

Sign Out
Sign In Register
NEW Insider PRO Learn More
Latest Insider
 * Get started with Anaconda Python
 * 11 tips for speeding up Python programs
 * Review: 7 Python IDEs go to the mat
 * BlazingSQL review: Fast ETL for GPU-based data science

NEW FROM IDG
Learn More
Analytics
Careers
Databases
Cloud Computing
 * Amazon Web Services
 * Kubernetes
 * Microsoft Azure

Machine Learning
Open Source
Software Development
 * Agile Development
 * CI/CD
 * Devops
 * Java
 * JavaScript
 * Microsoft .Net

Newsletters
IDG Events
In-Depth
 * Features
 * How-To
 * News
 * Reviews

Blogs
Video
 * Do More with R
 * Smart Python
 * IDG TECH(talk) Channel

White Papers/Webcasts
Welcome! Check out the latest Insider stories here.
Sign Out
Sign In Register
From Our Partners
   
   
 * The Latest Content from Our Sponsors

More from the Foundry Network
The voice of IT leadership
Analytics Careers CIO Role Digital Transformation Leadership Project Management
Security at the speed of business
Application Security Cloud Security Identity Management Information Security
Network Security Risk Management Security Software
Making technology work for business
Blockchain Collaboration Mobile Office Software Security Systems Management
Windows
From the data center to the edge
Data Center Internet of Things Linux Networking SD-WAN Servers Storage Wi-Fi
 * About Us |
 * Contact |
 * Republication Permissions |
 * Privacy Policy |
 * Cookie Policy |
 * Member Preferences |
 * Advertising |
 * Foundry Careers |
 * Ad Choices |
 * E-commerce Links |
 * California: Do Not Sell My Personal Info |

 * Follow Us
 * 
 * 
 * 


×

Close
 * Home
 * Software Development
 * Microsoft .NET

Microsoft Architect

By Joydip Kanjilal, Columnist, InfoWorld | Jan 6, 2022 3:00 am PST




DEMYSTIFYING THE PROGRAM AND STARTUP CLASSES IN ASP.NET CORE


PROGRAM AND STARTUP ARE THE MAIN CLASSES FOR CONFIGURING .NET APPLICATIONS.
LEARN HOW TO USE THEM IN ASP.NET CORE 6.

 * 
 * 
 * 
 * 
 * 
 * 
 * 


Thinkstock



ASP.NET Core 6 introduces a simplified hosting model that reduces the
boilerplate code that you would otherwise need to write to get your ASP.NET Core
application up and running. The Program and Startup classes are the two major
classes where you would typically write your code to configure your application.

This article talks about how you can configure the application start-up classes
in ASP.NET Core 6, with relevant code examples wherever appropriate.

[ ALSO ON INFOWORLD: WHAT’S NEW IN MICROSOFT .NET 6 ]

To work with the code examples provided in this article, you should have Visual
Studio 2022 installed in your system. If you don’t already have a copy, you can
download Visual Studio 2022 here.


CREATE AN ASP.NET CORE WEB API PROJECT IN VISUAL STUDIO 2022

First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following
these steps will create a new ASP.NET Core Web API 6 project in Visual Studio
2022:


 1.  Launch the Visual Studio 2022 IDE.
 2.  Click on “Create new project.”
 3.  In the “Create new project” window, select “ASP.NET Core Web API” from the
     list of templates displayed.
 4.  Click Next.
 5.  In the “Configure your new project” window, specify the name and location
     for the new project.
 6.  Optionally check the “Place solution and project in the same directory”
     check box, depending on your preferences.
 7.  Click Next.
 8.  In the “Additional Information” window shown next, select .NET 6.0 as the
     target framework from the drop-down list at the top. Leave the
     “Authentication Type” as “None” (default).
 9.  Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and
     “Enable Open API Support” are unchecked as we won’t be using any of those
     features here.
 10. Click Create.

This will create a new ASP.NET Core 6 Web API project in Visual Studio 2022.
We’ll use this project in the subsequent sections of this article.


WHAT IS A HOST IN .NET AND .NET CORE?

A .NET or .NET Core web application runs inside a host that handles application
startup, web server configuration, etc. The host encapsulates resources such as
logging, configuration, dependency injection (DI), and any IHostedService
implementations. A host is created, configured, and executed using the code
written in the Program class.



To create a host in ASP.NET Core 6, you should call the Build().Run() method on
a host builder. A host builder is an instance of IHostBuilder. The following
code snippet illustrates this:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Run();

The WebApplication class implements the following interfaces:

 * IHost – used to start and stop the host
 * IApplicationBuilder – used to build the middleware pipeline
 * IEndpointRouteBuilder – used to add endpoints

You can also call the CreateDefaultBuilder method to create a host. This method
is used to initialize a new instance of the WebHostBuilder class with
pre-configured defaults.

The following code snippet shows how the CreateDefaultBuilder method can be
used:

var host = new WebHostBuilder()
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseIISIntegration()
      .UseStartup<Startup>()
      .Build();

Note that both WebApplication and WebApplicationBuilder classes were introduced
in ASP.NET Core 6.

The ConfigureWebHostDefaults() extension method can be used to configure a web
application host by selecting Kestrel as the web server and configuring it using
the application’s hosting configuration providers.




THE PROGRAM CLASS IN .NET AND .NET CORE

A .NET or .NET Core project needs an entry point to start. The Main() method is
the entry point in a .NET or a .NET Core application. Because Main() is the
entry point of your application, you can have one and only one Main() method in
your project. Although you can put Main() anywhere in your project, it is
typically located in a class named Program, stored in a file called Program.cs.


THE PROGRAM CLASS IN ASP.NET CORE 5

Here is how a minimal Program class would look in .NET 5:

public class Program
{
      public static void Main(string[] args) {
            CreateHostBuilder(args).Build().Run();
      }
      public static IHostBuilder CreateHostBuilder(string[] args) {
            return Host.CreateDefaultBuilder(args).
            ConfigureWebHostDefaults(x => x.UseStartup <Startup> ());
      }
}


THE PROGRAM CLASS IN ASP.NET CORE 6

When you create a new Web API project in ASP.NET Core 6, you will have a
Program.cs file. However, unlike in ASP.NET Core 5 (and all previous versions of
ASP.NET Core), the project will not generate a Startup.cs file. The default
generated code of the Program class in ASP.NET Core 6 will look like this:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseAuthorization();
app.MapControllers();
app.Run();


THE STARTUP CLASS IN .NET AND .NET CORE

The Startup class contains the ConfigureServices and Configure methods. While
the former is used to configure the required services, the latter is used to
configure the request processing pipeline.



The Configure method is executed immediately after the ConfigureServices method.
Both of these methods are called by the runtime when the application starts. At
runtime, the .NET host passes an instance of IApplicationBuilder to the
Configure method. By default, the ConfigureServices adds the services to the
built-in container.

The following code listing illustrates how the Startup class is organized:

public class Startup
  {
        public void ConfigureServices(IServiceCollection services)
        {
            //Write code to add services to the container here
        }
        public void Configure(IApplicationBuilder app)
        {
         //Write code here to configure the request processing pipeline
        }
      //Other members have been removed for brevity
   }

You would also have a constructor in the Startup class which would be used to
initialize an IConfiguration instance, as illustrated in the code listing in the
next section.


USE THE STARTUP CLASS IN ASP.NET CORE 6

Although the Startup class is not generated by default in ASP.NET Core 6, you
can use the Startup class in ASP.NET Core 6 if you want to. To do this, you
should create a class named Startup (you can specify any other name as well) and
enter the ConfigureServices and Configure methods as shown below.

  public class Startup
  {
        public Startup(IConfigurationRoot configuration)
        {
            Configuration = configuration;
        }
        public IConfigurationRoot Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseEndpoints(x => x.MapControllers());
        }
   }

The UseRouting and UseEndpoints methods are used to add and configure the
routing middleware to the request processing pipeline. Your Program class code
should refer to the newly created Startup class. To do this, replace the
existing code of the Program class with the following code:

var builder = WebApplication.CreateBuilder(args);
var startup = new Startup(builder.Configuration);
startup.ConfigureServices(builder.Services);
var app = builder.Build();
startup.Configure(app);
app.Run();

Now set a breakpoint in the ConfigureServices and Configure methods of the
Startup class we created earlier. You’ll observe that the breakpoints are hit
when you run the application.

The new minimal hosting model in ASP.NET Core 6 enables you to write less
boilerplate code to get your application up and running. To maintain backward
compatibility, you can still use the Startup class in ASP.NET Core 6. You can
read more about the minimal hosting model in my previous article here.


Related:
 * Microsoft .NET
 * C#
 * Development Libraries and Frameworks
 * Web Development
 * Software Development

Joydip Kanjilal is a Microsoft MVP in ASP.Net, as well as a speaker and author
of several books and articles. He has more than 20 years of experience in IT
including more than 16 years in Microsoft .Net and related technologies.

Follow
 * 
 * 
 * 
 * 
 * 

Copyright © 2022 IDG Communications, Inc.

How to choose a low-code development platform



SPONSORED LINKS

 * Networks have never been more complex and cyber threats have never been more
   advanced. To protect it all, you need to see it all. That's Visibility
   Without Borders from Netscout.
 * CIS Webinar: Effective Implementation of the CIS Benchmarks & CIS Controls.
 * The cyber insurance market is getting tougher as premiums and the bar to get
   coverage go up
 * With Kolide, you can make your team into your biggest allies for endpoint
   security. Solve problems, right within Slack. Learn more here.
 * The Edge is the future—uncover the components of Edge success today and
   achieve your goal in becoming a modern, digital-first, and data-driven
   enterprise.
 * dtSearch® - INSTANTLY SEARCH TERABYTES of files, emails, databases, web data.
   25+ search types; Win/Lin/Mac SDK; hundreds of reviews; full evaluations

InfoWorld Follow us
 * 
 * 
 * 
   


 * About Us
 * Contact
 * Republication Permissions
 * Privacy Policy
 * Cookie Policy
 * Member Preferences
 * Advertising
 * Foundry Careers
 * Ad Choices
 * E-commerce Links
 * California: Do Not Sell My Personal Info

Copyright © 2022 IDG Communications, Inc.

Explore the Foundry Network descend
 * CIO
 * Computerworld
 * CSO Online
 * InfoWorld
 * Network World