Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Understanding Startup Class In ASP.NET Core

Understanding Startup Class In ASP.NET Core

07 Aug 2024
Beginner
3.79K Views
7 min read
Learn with an interactive course and practical hands-on labs

Free 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

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

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

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

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
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this