Skip to main content

ASP.NET Core Startup Class and Program.cs






Introduction.

Global.asax is no more in ASP.NET Core application. Startup.cs file is a replacement of Global.asax file in ASP.NET Core.

Startup.cs file is entry point of application level it handle request pipeline. Startup class which triggers at first when application launches.


Description.

Now question is startup.cs file is mandatory or not? Yes, startup.cs is mandatory, it can be decorated with any access modifier like public, private, internal. multiple Startup classes are allowed in a single application. ASP.NET Core will select the appropriate class based on its Enviroment.

If a class Startup{EnvironmentName} exists, that class will be called for that EnvironmentName.

Should we need to define class name with startup.cs? No it is not necessary that class name should be Startup.

We can define two method in startup file like ConfigureServices and Configure.

Startup file example :

public class Startup
{
    // Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        ...
    }

    // Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
        ...
    }
}



ConfigureServices Method :

This is an optional method in Startup class which is used to configure services for application. when any request come to application ConfigureService method will be called first.

ConfigureServices method includes IServiceCollection parameter to register services. This method must be declared with a public access modifier, so that 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 ConfigureServices method in startup class.

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc();
} 

Configure Method :

The Configure method is used to specify how the application will respond in each HTTP request. this method is mostly used for registering middleware in HTTP pipeline. this method method accept IApplicationBuilder parameter along with some other services like IHostingEnvironment and ILoggerFactory. Once we add some service in ConfigureService method, it will be available to Configure method to be used.

public void Configure(IApplicationBuilder app)
{
    app.UseMvc();
}

Above example shows to enable MVC feature in our framework we need to register UseMvc() into Configure and also need to register service AddMvc() into ConfigureServices.

Constructor for Startup Class :

We can specify parameterized constructor for startup file like IApplicationBuilder, IHostingEnvironment, IloggerFactory.

IApplicationBuilder : this interface contain properties and method related to current Enviroment.
IHostingEnvironment : this interface contain properties and method related to web hosting environment on which application is running.
IloggerFactory   : this interface provides configuration for the logging system.

Program.cs :

ASP.NET Core Program class file is place where we can create a host for the web application.

Example : 
public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup()
                .Build();
    }

WebHost is used to create instance of IWebHost and IWebHostBuilder. The CreateDefaultBuilder() method creates a new instance of WebHostBuilder.

the UseKestrel() specify method is extension, which specifies Kestrel as an internal web server. The Kestrel is an open-source, cross-platform web server for ASP.NET Core.

ASP.net Core is cross-platform and open-source and also it is compatible to host into any server rather than IIS, external web server such as IIS, Apache, Nginx etc.

When we want to host our application into iis we need to add UseIISIntegration() method specifies the IIS as the external web server.

UseStartup<startup>() method specifies the Startup class to be used by the web host. we can also specify our custom class in place of startup.

Build() method returns an instance of IWebHost and Run() starts web application till it stops.

Program.cs in ASP.NET Core makes it easy for us to setup a web host.


Comments

  1. ANTONIO CARDOSO SILVA JUNIOR15 June 2018 at 17:33

    Nice explanation about the subject.

    ReplyDelete
  2. The guidelines are adjusting, the type of console design is radically evolving, the presumptions we have concerning the primary design limits in creating a new activities machine must be re-evaluated.... Cryptocurrency

    ReplyDelete
  3. In running startups, it is important that your startup surpasses (or at least meets) your set goals; it shows that you're on the right track for future successes. However, where most startups get it wrong is the goal setting part. small businesses

    ReplyDelete
  4. I came to understand that entrepreneurship has been there for such countless years and that there are numerous individuals who can't characterize effectively who an entrepreneur is. Leadgeneratie

    ReplyDelete
  5. When alternatives to purchase enrollment units are given to representatives? When a favored class of participation units is characterized and given to financial backers? Obviously, the straightforwardness is no more. közúti szállítmányozás Europa-Road Kft

    ReplyDelete

Post a Comment

Popular posts from this blog

Custom AuthorizeAttribute in ASP.NET Core.

Introduction. Filter in MVC are attribute which can be apply to controller and action method. filters allow us to write our custom code before and after method execution. filters can be implemented into different level of scope Global, Class, and Method level. MVC provides different types of filters. The Authorization filter will run first and are used to determine whether the current user is authorized or unauthorized for the current request. In this article we will learn how to create custom authorization filter, were you can write your own authorization framework. Description. For creating Authorization filter IAuthorizationFilter interface must be inherited. For example, the following code demonstrate custom Authorization below CustomAuthorization attribute allow only Home controller to access the particular method under home controller class else it will return "error" in response if it is called via ajaxcall, otherwise it will be redirect to Sessi

What are PascalCase and CamelCase In Programing Language?

What are PascalCase and CamelCase In Programing Language?. Pascal Case  :-  In programming,  PascalCase   means that the first letter of every word in the name is capitalized. In Pascal Case if acronym exists in the word then only the first letter of that acronym should be capital. Eg:  ThisWordIsInPascalCase  . No other characters are used to separate the words, like hyphens or underscores. For example: BackColor TimeUtc FirstName CamelCase  :-    camelCase  or  CamelCase ; also known as  camel caps  or more formally as  medial capitals.  It is the same as Pascal Case, but the first letter of the first word is lowercased. this article calls the two alternatives  upper camel case  (initial upper case letter also known as Title Case) and  lower camel case  (initial lower case letter). Some people and organizations, notably  Microsoft  ,  use the term  camel case  only for lower camel case. For example: backColor timeUtc firstName Snake_case  :-PascalCase and camelCase

How to use Log4Net in .Net Core 2.0 Application.

1. Introduction Logging frameworks are important because they make it easy to write your logs to different places by simply changing your configuration. You can write your .NET logs to a file on disk, a database, a log management system 2. Install Nuget Package For nlog  To use Nlog logging you need to first add Nlog pluging for adding pluging you can do it by different way. 1) Manage Nuget Packages. 2) Nuget command. you can find nuget command for Log4Net below. PM> Install-Package log4net -Version 2.0.8 3. Add log4net.config file We need to Add New to your project with name log4net.config Refer below code for log4net.config for logging log into file. Root is neccesary in log4net.config, in which we can define log level and appender-ref in which we can define appender for eg. FileAppender, ConsoleAppender. Layout : In layout we can define custom parameter sh