Understanding Startup Class In ASP.NET Core

Understanding Startup Class In ASP.NET Core

07 Aug 2024
Beginner
2.55K Views
7 min read
Learn via Video Course & by Doing Hands-on Labs

Self-Paced ASP.NET Core Course

ASP.NET Core - Startup Class

The phrase ‘Startup class’ will come across regularly as we start working on our first web projects using ASP.NET Core. A Startup Class is the place at which you set up services and the app's request pipeline.

In this ASP.NET Core Tutorial, we will be discussing the Startup Class, its significance, and its relevance for assisting an application in starting and running. Do you want to know more about ASP.NET concepts? Then hurry up to join our Advanced ASP.NET Core Certification Training!

Why Startup Class?

The Startup class in ASP.NET Core is like the control center of your application. It's the place where you configure services and the app's request pipeline. Imagine it as the design for your application launch. This class is important because it guarantees that your app was correctly configured before that point where it begins serving HTTP requests.

Program Class for Applications Infrastructure

Before we go deeper into the Startup class, it's essential to understand its companion: the Program class. The Program class is where your application begins its execution. It contains the Main method, which is the entry point of your app. In the Main method, an instance of the web host is created, which then uses the Startup class to configure the application.

This is a simple example of how the Program class appears:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Thus, the CreateHostBuilder method specifies that the app configuration process should use the Startup class.

Read More: Salary Offered to ASP.NET Developers

Exploring the Startup Class

Now, let's talk about the Startup class itself. It typically consists of two methods that are, Configure and ConfigureServices in .NET Core. These methods are essential for setting up services and the app's request pipeline.
Here's a basic structure of the Startup class:
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // Register services here
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configure the HTTP request pipeline here
    }
}

Initializing with the Startup Constructor

The constructor of the Startup class is used to initialize the class and set up any required configuration. The IConfiguration instance is typically injected through the constructor to access configuration settings.
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
}

This setup ensures that you can easily access configuration settings throughout the Startup class.

Registering Services with ConfigureServices

The ConfigureServices method is used to include various facilities in an application. Such facilities are incorporated in the dependency injection container for access by any part of the application where they may be needed.
public void ConfigureServices(IServiceCollection services)
{
    // Register services here
    services.AddControllers();
    services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

This method allows you to add services, for example, MVC controllers, authentication, Entity Framework contexts etc.

Setting Up the Request Pipeline with Configure

The Configure method is where you set up the HTTP request pipeline. This pipeline defines how your app responds to HTTP requests.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

In this method, you configure middleware components like exception handling, HTTPS redirection, static files, routing, and more.

Where to Find the Startup Class?

By default, the Startup class is located at the root of your project. What you have automatically generated when a new ASP.NET Core project is created is a Startup class. Nevertheless, you can name this class in any other way; however, for the sake of maintaining simplicity and uniformity, it is normally referred to as the “Startup” class by default.

Key Services in the Startup Class

The Startup class provides access to various services, such as:
  • Configuration-Through dependency injection, you can access configuration settings.
  • Logging-Set up logging to monitor your application's behavior.
  • Dependency Injection-Register services and make them available throughout your application.
  • Environment-Determine the current environment (Development, Staging, Production) and configure your app accordingly.

These services are crucial for building robust and scalable applications.

Conclusion
This article explained about the Startup Class in ASP.NET Core. This class is essential for configuring your application's services and request pipeline. To learn about more such topics related to ASP.NET Core, consider enrolling in our ASP.NET Core Course.
Read More: Top 50 ASP.NET Core Interview Questions and Answers for 2024

FAQs

Q1. What is the Startup class in .NET Core?

The Startup class in .NET Core is the entry point where the services and request pipelines of the application are configured.

Q2. What is the Startup process in .NET Core?

The Startup process in .NET Core is where the Program class initializes the application and launches the Startup class.

Q3. Is .NET Core good for startups?

.NET Core offers high performance, a strong community, and cross-platform abilities, which makes it good for startups.

Q4. What is Owin Startup class?

The OWIN (Open Web Interface for .NET) Startup class is the startup class used with OWIN-based frameworks.

Take our Aspnet skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core ProjectOct 19SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this