Tuesday, February 12, 2019

How does ASP.NET Core Application initially starts?

ASP.NET Core application initially starts as a console application
  • It consists of Main method in its Program class which is the entry point 
  • Program class is located inside the root directory of the project

Main Method

  • Main method configures ASP.NET Core

public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); }

  • IWebHostBuilder, the return type of the WebHost.CreateDefaultBuilder has methods that define a web server and the startup class
  • The web server extension methods such as UseKestrel() for Kestrel server, UseIIS() for IIS server, UseHttpSys() for HTTPSys server, can be used
  • Kestrel web server is default server used by framework
    • Kestrel is a cross-platform web server for ASP.NET Core
    • It is the default web server included by ASP.NET Core project templates
  • The UseStartup method specifies the Startup class for your application
public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); }
  • The Startup class is where any services required by the app are configured and the request handling pipeline is defined.
  • The Build and Run methods build the IWebHost object that hosts the app and begins listening for HTTP requests

Monday, February 11, 2019

Middleware in ASP.NET Core

Middleware is the software component that is assembled into an application HTTP pipeline to handle requests and responses
  • Here, the Software component means the class which is executed on every request in ASP.NET Core application.
  • Typically, there will be multiple middleware in ASP.NET Core web application 
  • It can be either framework provided(built-in) Middleware, added via NuGet or your own custom middleware
The following figure illustrates the execution of middleware components:
Components in Middleware:
  • Chooses whether to pass the request to the next component in the pipeline.
  • Can perform work before and after the next component is invoked in the pipeline.

Configure Middleware


We can configure middleware in the Configure method of the Startup class using IApplicationBuilder instance.


  • In the above example, Run() is an extension method on IApplicationBuilder instance which adds a terminal middleware to the application's request pipeline
  • Request delegates are configured using RunMap, and Use extension methods

Run() extension method

  • At this point you might be worried about Run() method. So let me explain about the Run() method:
  • The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate
  • The signature of Run() method is,
public static void Run (this Microsoft.AspNetCore.Builder.IApplicationBuilder app, Microsoft.AspNetCore.Http.RequestDelegate handler);

  • Request delegates are used to build the request pipeline, and are configured using Run, Map and Use Extension methods
  • The Request delegate handle each HTTP request
  • The signature of RequestDelegate is,
public delegate System.Threading.Tasks.Task RequestDelegate(HttpContext context);

  • Since the RequestDelegate is the parameter of Run() method, it should accept the HttpContext parameter and return Task
  • You can either specify a lambda expression or specify a function in the Run method  as shown in figure below:
  • the above examples of configuring middleware using Run() method, both code snippet in above figure are equivalent

Use() extension method

  • We can use multiple request delegates together with Use() extension method 
  • It is similar to Run() method except that it includes next parameter. Consider the following example:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("This is from first Middleware!");

        await next();
    });

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("This is from second Middleware"); 
    });
}
  • When you run the above code, then it will display the following output on your browser:
  • The next parameter represents the next delegate in the pipeline. 
  • The middleware components can be used for following app scenarios:
    • Exception/error handling
    • HTTP Strict Transport Security Protocol
    • HTTPS redirection
    • Static file server
    • Cookie policy enforcement
    • Authentication
    • Session
    • MVC

public void Configure(IApplicationBuilder app) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //Middleware } else { app.UseExceptionHandler("/Error"); //Middleware } app.UseHttpsRedirection(); //Middleware app.UseStaticFiles(); //Middleware app.UseCookiePolicy(); //Middleware app.UseAuthentication(); //Middleware app.UseSession(); //Middleware app.UseMvc(); //Middleware }
  • The order that middleware components added in the Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response

Map() extension method

  • Map extensions are used for branching the pipeline
  • Map branches the request pipeline based on given request path
  • If the request path starts with the given path, the branch is executed

public class Startup { private static void MapRouteOne(IApplicationBuilder app) { app.Run(async context => { await context.Response.WriteAsync("Map Route One"); }); } private static void MapRouteTwo(IApplicationBuilder app) { app.Run(async context => { await context.Response.WriteAsync("Map Route Two"); }); } public void Configure(IApplicationBuilder app) { app.Map("/mapone", MapRouteOne); app.Map("/maptwo", MapRouteTwo); app.Run(async context => { await context.Response.WriteAsync("Hello World"); }); } }
The following figures shows the output of above example, at different map path.







Saturday, February 9, 2019

Application configuration in ASP.NET Core

  • In the previous versions of ASP .NET, any configuration setting or parameter you needed was added in web.config file
  • In ASP.NET Core, Configuration settings can be different configuration sources like:
    • Command-line arguments
    • Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment)
    • Environment variables
    • In-memory .NET objects
    • Custom configuration sources
  • App configuration in ASP.NET Core is based on key-value pairs established by configuration providers

appsettings.json file

  • appsettings.json file is located inside the root directory of the project, as you can see on below figure.
  • Configuration settings in ASP.NET Core usually stores in key-value pairs
  • Let me show you how to add a new key in appsettings.json file. I have added a key with name "keyMessage", as shown below:
  • To access Configuration information in the Startup class, inject the IConfiguration service provided by the Framework and used this object to read the specific key from appsettings.json
  • Here, in the above figure, you can see that I am using Dependency Injection. Dependency Injection is an integral part in ASP.NET Core
  • Now lets run the application and then you will see the output as "This message is from appsettings.json file".

Important points to know about IConfiguration service in ASP.NET Core
  • IConfiguration service is setup to read configuration information
  • Web apps based on the ASP.NET Core call WebHost.CreateDefaultBuilder method  which automatically invoked when application starts. CreateDefaultBuilder provides default configuration for the app.
  • Default App configuration is provided in the following order:
    • Here, the order means that the later configuration sources override the earlier configuration sources 
      • appsettings.json - using File Configuration Provider
      • appsettings.{Environment}.json - using File Configuration Provider
      • User Secretsusing Secret Manager (in the Development environment only)
      • Environment variablesusing the Environment Variables Configuration Provider
      • Command-line argumentsusing the Command-line Configuration Provider

    • If there is a configuration setting with the same key in multiple configuration sources, the later configuration sources override the earlier configuration sources
    • Now as for an example, I have setup appsettings.json file and appsettings.Development.json with key "keyMessage" using different values, as shown in figure below

    • Now run th application, you will see the output that the key value of appsettings.json file is overridden by appsettings.Development.json file
    • Similarly, add the same key on environment variables(in launchsettings.json file)

    • Now run the application using IIS Express profile(as new key is added to the Development environment of IIS Express profile as shown in figure above) & see the output:
    • Here you can see the output that, the key value of appsettings.Development.json file is overriden by the key value of environment variables.
    • Similarly, add the same key using Command-line and press enter
    • Now navigate to your browser and refresh the URL
    • You can see the output of command-line configuration source. Here all other sources are overridden by command-line source
  • You can change this order if you want to or even add your own custom configuration sources in addition to all the existing configuration sources.
Note: I will show you how to configure the application settings from custom configuration sources soon.

Wednesday, February 6, 2019

What is the use of launchsettings.json file in ASP.NET Core?

Keep in mind that, this file is only required on local development machine, we do not need it for publishing our ASP.NET Core application

launchsettings.json file is located inside the properties folder in solution explorer
Fig. 1. location
  • ASP.NET Core configures app behavior based on the runtime environment using an environment variable.
Fig. 2. launch profiles in asp.net core

  • This json file holds project specific settings associated with debug profile and launch of the application, including any environment variables that should be used
  • In the figure 2, it shows that there are 2 profiles(IIS Express & with same name as of project name) used in launchsettings.json
  • By default VS2017 uses the IIS Express as shown in Figure 2
  • Now lets see the output by running the application
Fig. 3. mapping browser url with launch profile
  • Notice in Figure 3, the Url with port number 3118 is mapped with iisSettings (Setting used for profile "IIS Express") of applicationUrl properties at launchsettings.json file
  • ASP.NET Core reads the environment variable ASPNETCORE_ENVIRONMENT at app startup and stores the value in IHostingEnvironment.EnvironmentName 
  • You can set ASPNETCORE_ENVIRONMENT to any value but,  by convention there are three values supported by the framework: DevelopmentStaging, and Production as shown in Figure 4
Fig. 4. Environment Variables
  • In the Figure 4, as for e.g. env.IsDevelopment() checks either the environment variable is set to Development or not, in the launchsettings.json file, as shown in the figure 2.
  • If ASPNETCORE_ENVIRONMENT isn't set, it defaults to Production
  • Now lets change the launch profile to MyFirstDotNetCoreApplication (this name will be your project name), from top of the visual studio and run the application, as shown in Figure 5
Fig. 5. Changed the profile to MyFirstDotNetCoreApplication
  • Now lets see the output
Fig. 6. Changed Profile Output
  • Notice in Figure 6, the Url used at above figure. Now it is mapped with MyFirstDotNetCoreApplication profile & at this time .NET Core CLI is used to launch the application that will popup another window for .NET Core CLI
  • Launch profiles can also be configured using the properties window of project. For this right-click on the project file and then you will see the window as shown in Figure 7.
Fig. 7. Profile changed from properties window of project
Now, just change the profile you want and run the application.


Monday, February 4, 2019

Setting up machine for asp.net core and creating first asp.net core web application

Before you begin:

Software

  • An Editor
    • You can choose different editors for asp.net core development like Visual Studio(VS), VS Code, Sublime etc.
  • Also the .NET Core SDK (Software Development Kit) is required to develop asp.net core application
  • I prefer and recommend VS as editor for asp.net core development for Windows OS & to download VS, visit the below link:
  • Visual Studio Community Edition is free to download and Install


  • During installation of VS 2017 – Select .NET Core Cross-Platform Development Workload
  • After the .NET Core cross-platform development tool-set is installed, Visual Studio usually installs a previous version of the .NET Core SDK. The current version of the .NET Core SDK as of this article is 2.2
To update Visual Studio to use .NET Core 2.2 SDK




  • Download and Install .NET Core SDK
  • To check installed version of .NET Core SDK
    • Go and Create a new asp.net core web application, and see the below dialog box


Create new .NET Core 2.2 project


Step 1 : Open visual studio, and then create new project







Step 2 : On the left side bar, select "Web" or ".NET Core" under Visual C#. There you will see the different project templates for .NET Core
  • Select "ASP.NET Core Web Application" template to create .NET Core Web Application
  • Provide the meaningful name of the project
  • Browse the project location
  • Click "OK"








Step 3 : After selecting the "ASP.NET Core Web Application" from step 2, it will display all the available templates for creating ASP.NET Core Web Application templates

  • "Web Application(Model-View-Controller)" automatically generates sample Models, Views, Controller and many other resources needed for building web application. It is also used to create RESTful HTTP Services

  • "API" templates includes the resources that are needed to build the RESTful HTTP Services. It does not contains the User Interface and other Web Specific things like Javascript, CSS, Views, etc.

  • "Web Application" project template is used for creating ASP.NET Core Application with example ASP.NET Core Razor Pages Content

  • "Razor Class Library" is used to create reusable Razor class library project, and can be used in multiple applications
  • "Empty template" is very cleanup to develop the application from beginning. It does not contains any content in it. I prefer to choose the Empty Templates to develop web application from beginning.
So now choose Empty template and uncheck "Configure for HTTPS" for now, and then click "OK"


Step 4 : After project created successfully, Run the project



Step 5 : Now you finally did it! You will see the "Hello World" as output on browser