Default files in an ASP.NET Core project
You have probably noticed by now that your empty project is not entirely empty, and does, in fact, include a couple of files:
- Program.cs: This is the entry point of the application. It loads configuration, initiates the logging framework, and more.
- Startup.cs: This is run when the web project starts. It configures the application services and requests pipeline components.
- The wwwroot folder: This folder is where all of the static assets of the application will be stored.
Configure Service Method
Declaration of this method is not mandatory in startup class. This method is used to configure services that are used by the application. When the application is requested for the first time, it calls ConfigureServices method. This method must be declared with a public access modifier, so that the environment will be able to read the content from metadata.
ASP.net core has built-in support for Dependency Injection. We can add services to DI container using this method. Following are ways to define the ConfigureServices method in startup class.
public void ConfigureServices(IServiceCollection services) {
services.AddMvc(); }
Configure Method
This method is used to define how the application will respond to each HTTP request i.e. we can control the ASP.net pipeline. This method is also used to configure middleware in the HTTP pipeline. This method accepts IApplicationBuilder as a parameter. This method may accept some optional parameters such as IHostingEnvironment and ILoggerFactory. Whenever any service is added to the ConfigureServices method, it is available to use in this method.
The Startup class
The Startup class is initialized and executed right after the web application starts. It is located under the project root folder in the Startup.cs file. This is where the application services and request pipeline components can be configured.
The Startup class contains two methods:
- ConfigureServices: This is where services will be added to the project. For example, this is where logging or authentication services are added.
- Configure: This is where services and request pipeline components are configured. For example, the settings for the authentication and logging services will be set here.
- Code execution order
- The Startup class is executed only once during an application’s lifespan, right after the webserver has loaded the ASP.NET Core application.
- The following screenshot shows the order of execution of the different methods in the classes involved in ASP.NET Core initialization:
The Startup class is not the place to put any code other than initialization and configuration code