This article applies to ASP.NET core version 3.0 to 5.0. You can visit program.cs in ASP.NET core to learn the latest version.
In this article, we will find the role of the startup class in ASP.NET Core. We learned how the Program class is responsible for creating a Web Host and configuring it. But, before building and running the host, the program class checks for startup class for further configuration. It invokes the Configure
& ConfigureServices
the method from the class. This allows us to further configure the App startup.
Table of Contents
What is Startup Class
The ASP.NET Core Startup (startup.cs) class is a simple class without inheriting from anything neither implementing any interface. But it is where we configure the request pipeline & middlewares. We also configure the services and add them to the dependency injection container. The class must contain the method Configure
and optionally it may contain the ConfigureServices
method.
It is similar to global.asax in classic ASP.NET.
Why Startup class?
The program & startup class are the two important places in ASP.NET Core apps. Virtually all the configuration of the App happens in these two files.
Program class for applications infrastructure.
The program class configures the application infrastructure
The program class creates the Web Host at the startup. it then configures the logging, DI Container. configuration system, Kestrel Web server, IIS Integration, etc. It also adds the framework services to the DI container so that we can use it. The code for the program class is automatically generated for us. And most probably enough for most of the projects.
The startup class for the application
Startup class is where we configure the components of the application.
We build services as our app grows. We need to add these classes in the DI Container. Also, we may need to set up and fine-tune the request pipeline. Startup class is where we do this.
The startup has two primary functions.
- Configure the services for dependency injection.
- It configures the request pipeline which handles all requests made to the application.
The following is an example of a startup class.
Location of the startup class
The startup
class is conventionally named as startup.cs
. It is located in the project route. Its location is configured in the Main
method of the program.cs
.
We learned about the Main method of the program.cs in the previous tutorial. The Main
method is the entry point of the application. It configures the WebHost, builds it and runs it. The host then receives the HTTP Requests and passes it to the request pipeline.
The WebHost calls the UseStartup method before building the WebHost.
1 2 3 4 5 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); //Startup class is registered here |
The UseStartup
method tells the WebHost
where to look for the startup class.
The name startup is not hardcoded. You can create a class by any name. For example, if you wish to use the AppStartup as the startup class, then remember to include it in the program as
1 2 3 | .UseStartup<AppStartup>() |
Services Available in Startup
The startup class does need the help of some of the Framework services so as to register & build request pipeline. The following framework services are already available for injection.
Services | Purpose |
IApplicationBuilder | We use this service to the application request pipeline. |
IHostingEnvironment | This service provides the current EnvironmentName, ContentRootPath, WebRootPath, and web root file provider |
ILoggerFactory | Provides a mechanism for creating loggers |
IServiceCollection | This is a DI container. We add services into this container. |
Method | Available Services |
Startup Constructor | IHostingEnvironment & ILoggerFactory |
ConfigureServices | IServiceCollection |
Configure | IApplicationBuilder, IHostingEnvironment & ILoggerFactory |
Startup class
ConfigureServices
The ConfigureServices is the method where we
- Configure the services.
- Add the services in the DI Container.
This method is optional. But if it exists, then it is the first method invoked by the WebHost.
The ConfigureServices
method expects services instance (of type IServiceCollection
) as the argument. The instance of the services is injected into the ConfigureService
via Dependency Injection.
1 2 3 | public void ConfigureServices(IServiceCollection services) { |
IServiceCollection
is a DI container. We add services into this container. The following code is an example of how we use AddMvc()
extension method to add MVC related services to the IServiceCollection
collection
1 2 3 | services.AddMvc(); |
Adding services to the Dependency Injection container will make them available for dependency injection. That means we can inject those services anywhere in our application. Dependency Injection is one of the new features of ASP.NET Core. The ASP.NET Core uses the dependency injection extensively.
The example below shows a typical ConfigureServices
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 | public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc(); } |
Configure
The Configure
method is a must. It is invoked after the ConfigureServices
method.
The configure method allows us to configure the ASP.NET Core request pipeline. The Request pipeline specifies how the application should respond to HTTP requests.
The Components that make up the request pipeline are called middleware.
A Typical Configure method is shown below. This is the configure
method Visual Studio generates if you choose the MVC Web Application (MVC) template.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseCors("AllowAll"); app.UseAuthentication(); app.UseMvc(routes => routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } |
The Configure
method asks for an instance of IApplicationBuilder
and HostingEnvironment
. The code above does not inject the ILoggerFactory
, but we can do that.
1 2 3 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) |
We, then add our middleware components to the instance of IApplicationBuilder
instance (app).
The first line checks to see if we are under a development environment. If yes it registers the DeveloperExceptionPage
middleware using the extension method UseDeveloperExceptionPage
1 2 3 4 5 6 | if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } |
In the subsequent lines, we register three more middlewares.
1 2 3 4 5 | app.UseStaticFiles(); app.UseCors("AllowAll"); app.UseAuthentication(); |
The last line of code registers the MVC Middleware. The Routes are configured while registering the Middleware.
1 2 3 4 5 6 7 | app.UseMvc(routes => routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); |
If you have followed out Hello World Example Application, you will see the following configure
method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } |
Here, we use the run
method of the app to register the inline middleware. The code writes Hello World
to the response object.
Summary
The Startup (startup.cs) class is where we configure the components of our app. The Optional ConfigureServices
method is where we register our services for DI. The Configure
method is where we set up requests pipeline. The CreateDefaultBuilder method then reads the startup to configure the web host, before building and running it.
These tutorials are awesome. Thank you for the efforts!!
Hi. Thank you for the fantastic tutorial.
Just wanted to let you know that the next article https://www.tektutorialshub.com/asp-net-core/asp-net-core-kestrel-web-server/
doesn’t seem to be working, just in case you weren’t aware.
Be great to be able to read the article!
Thanks again.
Thanks!