You are currently viewing Asp .Net Core – 6 Lesser Known Facts

Asp .Net Core – 6 Lesser Known Facts

Asp .Net core is really gaining the popularity. Visual studio has provided marvelous project template. This project template adds code to do many things.

While we all understand the primary intention of using any IDE, is to speed up the application development, I believe it is immensely important to understand the basics of how these things internally works. This surely helps in better use of the technology.

This article provides light on such few facts which all curious minds should know.

Web Servers

There are at least three different web servers which can be used to host the asp.net core web applications. You can use any of below mentioned servers:

  • Kestrel – this is the default option. Even when you don’t specify the server, this server is used. This web server is also available on MacOS and on Linux.
  • IIS – Our favourite IIS server (windows 7 or later) can also be used to host the Asp .Net core web site. By default CreateDefaultBuilder calls UseIIS method.
  • HTTP.sys -Below sample code shows how to configure Http.Sys configurations.

If you use http.sys, then you will not be able to host the application in IIS as HTTP.sys is not compatible with AspNetCore module.

  
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
     .UseStartup<Startup>()
     .UseHttpSys(options =>
     {
         // The following options are set to default values.
         options.Authentication.Schemes = AuthenticationSchemes.;
         options.Authentication.AllowAnonymous = true;
         options.MaxConnections = null;
         options.MaxRequestBodySize = 30000000;
         options.UrlPrefixes.Add("http://localhost:44334");
     });

Startup

The Main method is called when the Asp .Net core app is initiated. It calls the CreateDefaultBuilder method to initiate the web host. We will have a detailed look at what this method does sometime in my subsequent articles. But this method starts the web server, applies some settings to web host and initializes the configurations.

The code also tells to use a special class with name Startup for adding more services or adding more middleware in the request process pipelines.

This startup class has two methods :

  • ConfigureServices – to add new services (e.g. database server, cache server, authentication etc.)
  • Configure – is to customize the request process pipeline by configuring which middleware should be used.

You can also write these methods inline in the CreateWebHostBuilder method instead of having it as a separate class. I still prefer having it has a separate file as it makes the code look a bit clean.

Environment Variables

During startup, Asp .Net core reads all the environment variables which start with “ASPNETCORE_”.

The “ASPNETCORE_ENVIRONMENT” is used to decide the environment. Three values supported by .Net core by default are- Development, Staging and Production. If you don’t specify this value, then by default production is used.

You can also use your own value. For. ex you can use value like “automation_test”. You can check this during Configure method in app startup and decide which middlewares should be initialized.

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
{     
    if (env.IsDevelopment())     
    {
         app.UseDeveloperExceptionPage();     
    }    
 
    if (env.IsProduction() || env.IsStaging() 
           ||env.IsEnvironment("automation_test"))
    {
         app.UseExceptionHandler("/Error");
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseMvc();
}

Middleware

People who are familiar with Web Forms and Asp.Net MVC, may compre this with HTTP Modules or with MVC Filters.

Middleware are based on the similar concept – they are gatekeepers. You can configure them in Startup.cs in Configure method.

They are called one after the other. They can either modify the request before passing it to next OR they can provide the response before even handing this request over to controllers (often called as shorting of request/response pipleline). Some of the examples are:

  • routing the reuqests to appropriate controllers actions.
  • custom logging
  • custom exception handling

Dependency Injection

In Asp .Net core app, you may often see that constructure is taking parameters and class is directly using it – without explicitly creating object of that type. You may wonder how it is happening. The answer is DI through Unity IoC container.

Asp .Net Core uses the unity container as its default IoC container (IoC – Inversion of control – a design pattern). The idea is if your class dependent on some other classes for some reasons, you should not create its object using “new” operator. The IoC container will instantiate all the dependencies. This instantiation will be based on the configurations done during startup.

HttpContext

People moving from Asp.Net MVC 5 may want to reuse their UI layer code by referring the old libraries.

Please note that System.Web pipeline is not executed for Asp.Net core application. Hence the HttpContext.Current – which is MVC5 representation of HTTP context – is not instantiated at all. So, if you are referring to any library method – which internally uses HttpContext.Current[sessionKey], you will get exception.

It is very important to understand that Asp .Net core provides HttpContext object and it is accessible in Razor views and MVC classes (e.g. controllers, filters, etc.).

In case you want to use HttpContext where it is not accessible, the default implementation of IHttpContextAccessor will be useful. So, you can inject IHttpContextAccessor and then you will be able to use the HTTP Context as shown below

public void ConfigureServices(IServiceCollection services)
{
	services.AddMvc();
	services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

public class SomeClass
{
    IHttpContextAccessor httpContextAccessorInstance;
    public SomeClass(IHttpContextAccessor accessor)
    {
        httpContextAccessorInstance = accessor;
    }

    public void DoWork()
    {
         //// Some Code
         var httpContext = httpContextAccessorInstance.HttpContext
         
         //// Do some work with httpContext now.
    }
}

I hope this article helped you to understand these hidden / ignored facts. Please comment and let me know if there is any specific thing you want me to explain in any future articles.

Leave a Reply

This Post Has 2 Comments

  1. Niraj Sonawane – Pune – I am Software Developer from India. My career spanning more than 10 years has been mostly in the financial domain and I had the privilege to be associated with and contribute to some of the leading brands in the financial sector. My Passion is to be Write Clean,Elegant and Scalable Code. I love to follow latest trends and Best Practices in software engineering. I am a strong believer that success lies in balancing the fine line between YAGNI and “do it right the first time” coding philosophies. Creating a good software is not a one time activity but it’s continually evolving process.
    Niraj Sonawane

    Cool stuff Manoj…. thanks for sharing