The Startup class in ASPNET Core

This tutorial explains the Startup class in ASP.NET, along with the methods of this class. We also explain how a custom middleware can be attached by IStartupFilter.
(Rev. 18-Jun-2024)

Categories | About |     |  

Parveen,

Purpose of Startup.cs

  1. to configure app services [for example, for database access]
  2. to specify how the app responds to HTTP requests.

Methods in the Startup class

  1. Constructor:
    public Startup(IWebHostEnvironment env, IHostEnvironment henv, IConfiguration config)
    {
    
      // cache useful instances 
      _env = env;
    
      _henv = henv;
    
      _config = config;
    
    }
    
    

    The host provides [injects] all available services to the Startup constructor.

    If Generic Host is used [as in the default ASP.NET core template], then the run-time injects these three services - IWebHostEnvironment, IHostEnvironment and IConfiguration.

    This method is optional.

  2. ConfigureServices Method:

    The app can add additional services by writing code in this method.

    Examples of additional services: (i) services for enabling razor pages, (ii) DbContext for database connectivity, etc., (iii) and your own classes with public methods are also called services.

    This method is optional.

    Called by the runtime before the Configure method.

    public void ConfigureServices(IServiceCollection services)
    {
    
      services.AddSingleton<IMyClass, CMyClass>();
    
    }
    
    
  3. Configure Method:

    The host services as well as the app services are all available in the Configure method so that app's request pipeline can be programmed.

    IApplicationBuilder instance is available only in this method. It is used to configure the middleware for processing http requests.

    This method must be coded for your application to serve pages or data.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    
      app.UseRouting();
    
      app.UseEndpoints(endpoints =>
    
      {
    
        endpoints.MapGet("/", async context =>
    
        {
    
          await context.Response.WriteAsync("Hello World!");
    
        });
    
      });
    
    }
    
    

Multiple Startup classes

If both the classes - Startup and StartupDevelopment are included then StartupDevelopment is used during development environment because of the suffix.

How to configure without Startup

Use the ConfigureServices and Configure methods on ConfigureWebHostDefaults as here:

Host.CreateDefaultBuilder(args)
.ConfigureLogging((config) =>

{

  config.ClearProviders();

  config.AddConsole();

})

.ConfigureWebHostDefaults(webBuilder =>

{

  webBuilder.ConfigureServices((services) =>

  {

    services.AddSingleton<IMyClass, CMyClass>();

  });

  webBuilder.Configure(app =>

  {

    // webBuilder.UseStartup<Startup>(); 

    var env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();

    var config = app.ApplicationServices.GetRequiredService<IConfiguration>();

    // using Microsoft.AspNetCore.Builder; 

    app.UseRouting();

    app.UseEndpoints(endpoints =>

    {

      endpoints.MapGet("/", async context =>

      {

        await context.Response.WriteAsync("Hello World!");

      });

    });

  });

});

IStartup Filters

Used to ensure that custom middleware runs before or after the middleware pipeline configured through the Startup class.

This is a middleware class that writes a small text to the response.

class MyPreMiddleware
{

  private readonly RequestDelegate _next;

  public MyPreMiddleware(RequestDelegate next)
  {

    _next = next;

  }

  public async Task Invoke(HttpContext httpContext)
  {

    await httpContext.Response.WriteAsync("Hi");

    await _next(httpContext);

  }

}

Next we need an IStartupFilter to configure the call to the above component

class MyPreFilter : IStartupFilter
{

  public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
  {

    return builder =>

    {

      builder.UseMiddleware<MyPreMiddleware>();

      next(builder);

    };

  }

}

Register the IStartupFilter

public static IHostBuilder CreateHostBuilder(string[] args) =>

Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>

{

  webBuilder.UseStartup<Startup>();

})

.ConfigureServices(services =>

{

  services.AddTransient<IStartupFilter, MyPreFilter>();

});

}

Comments and Discussion

Please write your comments and discussion on the following youtube video itself:


This Blog Post/Article "The Startup class in ASPNET Core" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.