MSDN Documentation

ASP.NET Core Startup

This document provides a comprehensive overview of the Startup class in ASP.NET Core. The Startup class is the entry point for configuring your application's services and request pipeline.

The Role of the Startup Class

When an ASP.NET Core application starts, the runtime looks for a class named Startup in the application's root namespace. This class is responsible for:

  • Registering application services in the dependency injection container.
  • Configuring the HTTP request pipeline.

Startup Class Configuration

The Startup class typically has two main methods:

1. ConfigureServices

This method is used to register services with the application's dependency injection container. Services are the building blocks of your application, such as data access components, business logic classes, and MVC controllers.


public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    // Add application services.
    services.AddTransient<IMyService, MyService>();
}
                

2. Configure

This method is used to configure the application's HTTP request pipeline. The request pipeline is a series of components (middleware) that process incoming HTTP requests and outgoing HTTP responses.


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

    app.UseStaticFiles(); // Serve static files
    app.UseMvc();        // Add MVC to the request pipeline
}
                

Middleware in the Request Pipeline

Middleware components are executed in the order they are added to the request pipeline. Common middleware includes:

  • DeveloperExceptionPageMiddleware: Displays detailed exception information in development environments.
  • StaticFilesMiddleware: Serves static files like HTML, CSS, and JavaScript.
  • RoutingMiddleware: Matches incoming requests to endpoints.
  • AuthenticationMiddleware: Handles user authentication.
  • AuthorizationMiddleware: Enforces access control.
  • MVC Middleware: Handles MVC-specific request processing.

Advanced Configuration

For more complex scenarios, you can use features like:

Understanding the Startup class is fundamental to building robust and scalable ASP.NET Core applications. Explore the related documentation for deeper insights into each component.