Thursday, 24 September 2020

ASP.NET Core - Middleware

 ASP.NET Core introduced a new concept called Middleware. A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request.

Typically, there will be multiple middleware in ASP.NET Core web application. It can be either framework provided middleware, added via NuGet or your own custom middleware. We can set the order of middleware execution in the request pipeline. Each middleware adds or modifies http request and optionally passes control to the next middleware component. The following figure illustrates the execution of middleware components.


Middleware's build the request pipeline. The following figure illustrates the ASP.NET Core request processing.

Configure Middleware

We can configure middleware in the Configure method of the Startup class using IApplicationBuilder instance. The following example adds a single middleware using Run method which returns a string "Hello, World!" on each request.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello, World!");
        });
    }
}

In the above example, Run() is an extension method on IApplicationBuilder instance which adds a terminal middleware to the application's request pipeline. The above configured middleware returns a response with a string "Hello World!" for each request.

To configure multiple middleware, use Use() extension method. It is similar to Run() method except that it includes next parameter to invoke next middleware in the sequence. Consider the following example.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Hello World From 1st Middleware!");

        await next();
    });

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World From 2nd Middleware"); 
    });
}

The above example will display Hello World From 1st Middleware!Hello World From 2nd Middleware! in the browser.

Thus, we can use Use() method to configure multiple middlewares in the order we like.

Add Built-in Middleware Via NuGet

ASP.NET Core is a modular framework. We can add server side features we need in our application by installing different plug-ins via NuGet. There are many middleware plug-ins available which can be used in our application.

The followings are some built-in middleware:

1. Exception Handling:

  • UseDeveloperExceptionPage() & UseDatabaseErrorPage(): used in development phase to catch run-time exceptions.
  • UseExceptionHandler("/Error"): used in production for run-time exceptions

Calling these methods first ensures that exceptions are caught.

2. HSTS & HTTPS Redirection:

  • UseHsts(): HTTP Strict Transport Security Protocol (HSTS) Middleware (UseHsts) adds the Strict-Transport-Security header.
  • UseHttpsRedirection(): forces HTTP calls to automatically redirect to equivalent HTTPS addresses.

Calling these methods next ensure that HTTPS can be enforced before resources are served from a web browser.

3. Static files:

  • UseStaticFiles(): used to enable static files, such as HTML, JavaScript, CSS and graphics files.

This Middleware is called early on to avoid the need for authentication, session or MVC middleware.

4. Cookie Policy:

  • UseCookiePolicy(): used to enforce cookie policy and display GDPR-friendly messaging

5. Authentication, Authorization & Sessions:

  • UseAuthentication(): used to enable authentication and then subsequently allow authorization.
  • UserSession(): manually added to the Startup file to enable the Session middleware.

Calling these after cookie authentication (but before the MVC middleware) ensures that cookies can be issued as necessary and that the user can be authenticated before the MVC engine kicks in.

6. MVC & Routing:

  • UseMvc(): enables the use of MVC in your web application, with the ability to customize routes for your MVC application and set other options.
  • routes.MapRoute(): set the default route and any custom routes when using MVC.
Middleware Ordering
 
Middleware components are executed in the order they are added to the pipeline and care should be taken to add the middleware in the right order otherwise the application may not function as expected. This ordering is critical for security, performance, and functionality.
 
The following middleware components are for common app scenarios in the recommended order:


The first configured middleware has received the request, modify it (if required), and passes control to the next middleware. Similarly, the first middleware is executed at the last while processing a response. That’s why Exception-handling delegates need to be called early in the pipeline, so they can validate the result and displays a possible exception in a browser and client-friendly way.




Reference: https://medium.com/, https://docs.microsoft.com


Continue Reading →

Wednesday, 23 September 2020

ASP.NET Core Startup Class

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 class triggers at first when application launches.

The Startup class is a place where:

  1. Services are configured which are required by the application .
  2. The app's request handling pipeline is defined, as a series of middleware components.

Description.
Startup.cs is mandatory in the application, 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.

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.

Continue Reading →

Thursday, 10 September 2020

ASP.NET State Server

 How to Store Session Data in ASP.NET State Server

ASP.NET Session State allows four modes to specify where you want to store session data: InProc, SQLServer, State Server and Custom. Default mode InProc, is fastest and default mode, but not useful in many scenarios. One of the significant problems is that sessions stored InProc are deleted every time when application restarts. This could happen pretty often.

If your user was in the middle of long task like populating long order form or survey; or reading of license agreement etc., all his previously saved session data will be lost, and he or she must start process from the beginning.

Also, default InProc mode doesn't support multiple servers (web farms) and multiple processors (web gardens). If your website is running on multiple web servers or multiple processors, you have to keep sessions out of ASP.NET process.

As solution for all of these problems, as more reliable and scalable options, ASP.NET introduces State Server and SQL Server. Both State Server and SQL Server stores sessions outside of ASP.NET process, so they are appropriate solution for web farm scenario.

What is ASP.NET State Server?

State Server is implemented as Windows service. File of State Server is aspnet_state.exe. This file is located on [SystemFolder]\Microsoft.Net\Framework\[.Net Framework Version Number]\aspnet_state.exe. Example location for ASP.NET 4.0 could be:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_state.exe

How to use Session State service

First, be sure that State Server windows service is running. Check in Windows Control Panel --> Services and assure that "ASP.NET State Service" is started. You can also start state service using command prompt with line:

 net start aspstate 

By default, State Server service is set up to start manually. Change startup type to Automatic so it will run again if computer restarts.

Second step is to edit <sessionState> element in web.config to configure ASP.NET web application to use State Server. Like this:

<sessionState mode="StateServer"  stateConnectionString="tcpip=127.0.0.1:42424" />

That is all. Now you can start ASP.NET application and session data will be stored out of application process, in State Server.

Reference1, Reference2

Continue Reading →

Saturday, 29 August 2020

Tag Helpers ASP.NET Core

 What are Tag Helpers

Tag Helpers are server side components. They are processed on the server to create and render HTML elements in Razor files. If you have any experience with previous version of ASP.NET MVC, then you may be familiar with HTML helpers. Tag Helpers are similar to HTML helpers. There are many built-in Tag Helpers for common tasks such as generating links, creating forms, loading assets etc.

Importing built-in Tag Helpers

To make the built-in tag helpers available for all the views in our entire application, import the tag helpers using _ViewImports.cshtml file. To import tag helpers we use @addTagHelper directive.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The wildcard * indicates that we want to import all the tag helpers.

Microsoft.AspNetCore.Mvc.TagHelpers is the assemly that contains the built-in tag helpers

Generating Links using Tag Helpers

Let's say we want to view a specific employee details. So we want to generate the following hyperlink. The number 5 is the ID of the employee whose details we want to view.

/home/details/5

There are several ways we could do this in a razor view

Option 1 : Manually generating the links

@foreach (var employee in Model)
{
    <a href="/home/details/@employee.Id">View</a>
}


Option 2 :
Using HTML helpers

@Html.ActionLink("View", "details", new { id = employee.Id })


generates an anchor element

<a href="/hom/details/5">View</a>

@Url.Action("details", "home", new { id = employee.Id })


generates a string

/hom/details/5

Option 3 : Using Tag Helpers

<a asp-controller="home" asp-action="details" asp-route-id="@employee.Id">View</a>

generates

<a href="/Home/details/5">View</a>


Anchor Tag Helper

The Anchor Tag Helper enhances the standard HTML anchor (<a ... ></a>) tag by adding new attributes such as 

asp-controller
asp-action
asp-route-{value}

The rendered anchor element's href attribute value is determined by the values of these asp- attributes. 

As the names imply asp-controller specifies the controller name and asp-action specifies the action name to include in the generated href attribute value. asp-route-{value} attribute is used to include route data in the generated href attribute value. {value} can be replaced with the route parameters such as id for example.

<a asp-controller="home" asp-action="details" asp-route-id="@employee.Id">View</a>

Advantage of using Tag helpers
Tag helpers generate links based on the application routing templates. This means if we later change routing templates, the links generated by tag helpers will automatically reflect those changes made to the routing templates. The generated links just work. 

Where as if we have hard-coded the URL paths manually, we would have to change the code in lot of places when the application routing templates change. Click here

ASP.NET Core Image tag helper
Image Tag Helper can help us achieve this. To use the Image tag helper, include asp-append-version attribute and set it to true.

<img src="~/images/noimage.jpg" asp-append-version="true" />

Image Tag Helper enhances the <img> tag to provide cache-busting behavior for static image files. Based on the content of the image, a unique hash value is calculated and is appended to image URL. This unique string prompts the browser to reload the image from the server and not from the browser cache.

<img class="card-img-top"
src="/images/noimage.jpg?v=IqNLbsazJ7ijEbbyzWPke-xWxkOFaVcgzpQ4SsQKBqY" />

Each time the image on the server changes a new hash value is calculated and cached. If the image has not changed the hash isn't recalculated. Using this unique hash value, the browser keeps track of whether the image content on the server has changed. Click here

ASP.NET Core Environment Tag Helper
Environment tag helper supports rendering different content depending on the application environment. The application environment name is set using using ASPNETCORE_ENVIRONMENT variable.

This example loads the non-minified bootstrap css file, if the application environment is "Development"

<environment include="Development">
    <link href="~/lib/bootstrap/css/bootstrap.css" rel="stylesheet" />
</environment>

This example loads the minified bootstrap css file from the CDN (Content Delivery Network), if the application environment is "Staging" or "Production".

<environment include="Staging,Production">
    <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
</environment>

"include" attribute accepts a single hosting environment name or a comma-separated list of hosting environment names. On the <environment> tag helper, we also have "exclude" attribute. The content of the <environment> tag is rendered when the hosting environment doesn't match an environment listed in the exclude attribute value.

The "integrity" attribute on the <link> element is used for Subresource Integrity check. Subresource Integrity (SRI for short), is a security feature that allows a browser to check if the file being retrieved has been maliciously altered. When the browser downloads the file, it recalculates the hash and compares it against the "integrity" attribute hash value. If the hash values match, the browser allows the file to be downloaded otherwise it is blocked. Click here

Form tag helpers in asp.net core

We use the following common tag helpers to create a form in ASP.NET Core.  Click here for more
  • Form Tag Helper
  • Label Tag Helper
  • Input Tag Helper
  • Select Tag Helper
  • Textarea Tag Helper
Form Tag Helper:
<form asp-controller="home" asp-action="create" method="post">
</form>

Input Tag Helper:
The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.

@model Employee

<input asp-for="Name">

Label Tag Helper:
The Label Tag Helper generates a label with for attribute. The for attribute links the label with it's associated input element. Consider the following example.

<label asp-for="Name"></label>
<input asp-for="Name">

//The above code generates the following HTML. 

<label for="Name">Name</label>
<input type="text" id="Name" name="Name" value="">

Select Tag Helper:
Generates select element and it's associated option elements.

namespace EmployeeManagement.Models
{
    public enum Dept
    {
        None,
        HR,
        Payroll,
        IT
    }
}

<label asp-for="Department"></label>
<select asp-for="Department"
        asp-items="Html.GetEnumSelectList<Dept>()"></select>

Notice, we are using asp-items tag helper and Html.GetEnumSelectList<Dept>() to get the options for the select element.

Create.cshtml - Complete Code without Bootstrap
@model Employee

@{
    ViewBag.Title = "Create Employee";
}

<form asp-controller="home" asp-action="create" method="post">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
    </div>

    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email">
    </div>

    <div>
        <label asp-for="Department"></label>
        <select asp-for="Department"
                asp-items="Html.GetEnumSelectList<Dept>()"></select>
    </div>
    <button type="submit">Create</button>
</form>



Continue Reading →

Tuesday, 25 August 2020

ASP NET Core appsettings json file

 ASP.NET Core appsettings.json file

Configuration Sources in ASP.NET Core

In previous versions of ASP.NET, we store application configuration settings, like database connection strings for example, in web.config file. In ASP.NET Core application configuration settings can come from the following different configurations sources.

  1. Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment)
  2. User secrets
  3. Environment variables
  4. Command-line argument

appsettings.json file : In the asp.net core project that is generated by the "Empty" project template we already have a file with name appsettings.json. I have modified this file to include a new setting with the key - MyKey.

{
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts": "*",
    "MyKey": "Value of MyKey from appsettings.json"
  }


Accessing configuration information 

To access configuration information in the Startup class, inject the IConfiguration service provided by the Framework. Startup class is in Startup.cs file.

public class Startup
{
    private IConfiguration _configuration;

    // Notice we are using Dependency Injection here
    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(_configuration["MyKey"]);
        });
    }

    var ResLog= Configuration.GetSection("ResponseLogging").Value ;
    var CorsHeader= Configuration.GetValue<string>("Cors:Headers");
}


ASP.NET Core IConfiguration service

  1. IConfiguration service is setup to read configuration information from all the various configuration sources in asp.net core
  2. If you have a configuration setting with the same key in multiple configuration sources, the later configuration sources override the earlier configuration sources 
  3. CreateDefaultBuilder() method of the WebHost class which is automatically invoked when the application starts, reads the configuration sources in a specific order.
  4. To see the order in which the configuration sources are read, please check out ConfigureAppConfiguration() method on the following link github.com

Upon inspecting the file, you will see, the following is the default order in which the various configuration sources are read

  1. appsettings.json, 
  2. appsettings.{Environment}.json
  3. User secrets
  4. Environment variables
  5. Command-line arguments

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. 


Continue Reading →

ASP.NET Core InProcess/OutOfProcess hosting

InProcess Hosting in ASP.NET Core

When an ASP.NET core application is executed, the .NET runtime looks for Main() method which is the entry point for the application. The Main() method then calls CreateDefaultBuilder() static method of the WebHost class. 

This CreateDefaultBuilder() method performs several tasks like 

  1. Setting up the web server 
  2. Loading the host and application configuration from various configuration sources and 
  3. Configuring logging

An ASP.NET core application can be hosted InProcess or OutOfProcess. here we will discuss only InProcess.

With InProcess hosting, the application is hosted in the IIS worker process (w3wp.exe or iisexpress.exe). With InProcess hosting, there is only one web server and that is the IIS server that hosts our application.

InProcess hosting in ASP.NET Core

To configure InProcess hosting, add <AspNetCoreHostingModel> element to the app's project file with a value of InProcess

<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

When we create a new ASP.NET Core project using one of the available project templates, the project defaults to the in-process hosting model for all IIS and IIS Express scenarios.

In case of InProcess hosting, CreateDefaultBuilder() method calls UseIIS() method and host the app inside of the IIS worker process (w3wp.exe or iisexpress.exe). 

  1. From a performance standpoint, InProcess hosting delivers significantly higher request throughput than OutOfProcess hosting
  2. In the case of IIS, the process name that executes the app is w3wp and in the case of IIS Express it is iisexpress
  3. To get the process name executing the app, use System.Diagnostics.Process.GetCurrentProcess().ProcessName
  4. When we are run the project from Visual Studio it uses IISExpress by default. 
  5. IIS Express is a lightweight, self-contained version of IIS, optimized for application development. We do not use it for production. In production we use IIS.

Out of Process Hosting in ASP.NET Core

To configure an app for out-of-process hosting, set the value of the <AspNetCoreHostingModel> property to OutOfProcess in the project file (.csproj):

<PropertyGroup>
  <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
</PropertyGroup>

In-process hosting is set with InProcess, which is the default value.

The value of <AspNetCoreHostingModel> is case insensitive, so inprocess and outofprocess are valid values.

Kestrel server is used instead of IIS HTTP Server (IISHttpServer).
For out-of-process, CreateDefaultBuilder calls UseIISIntegration to:

  1. Configure the port and base path the server should listen on when running behind the ASP.NET Core Module.
  2. Configure the host to capture startup errors.

There are 2 web servers - An internal web server and an external web server. 

  • The internal web server is Kestrel and the external web server can be IIS, Nginx or Apache.
  • With InProcess hosting, there is only one web server i.e the IIS that hosts the asp.net core application. 

Depending on how you are running the asp.net core application, the external web server may or may not be used. 

What is Kestrel

Kestrel is a cross-platform web server for ASP.NET Core. When we run a .NET Core application using the .NET Core CLI (Command-Line Interface), the application uses Kestrel as the web server. 

The .NET Core CLI is a cross-platform tool for developing .NET core applications. Using the CLI we can

  1. Create a new project, configuration file, or solution based on the specified template
  2. Restore the dependencies and tools required for a .net core project
  3. Build a project and all of its dependencies
  4. Run a project etc...

Reference: Click here

Continue Reading →

Main method in asp.net core

 In an ASP.NET Core project we have seen a file with named Program.cs. In this file we have a public static void Main() method.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

If you have any experience with previous versions of .NET, a console application has a Main() method and it is the entry point for that console application.

But here, we are creating an asp.net core web application and not a console application. So the obvious question that comes to our mind is why do we have a Main() method.

Well, the important point to keep in mind is that, an asp.net core application initially starts as a console application and the Main() method in Program.cs file is the entry point. 

So, when the runtime executes our application it looks for this Main() method and execution starts.

This Main() method configures asp.net core and starts it and at that point it becomes an asp.net core web application.

So, if you take a look at the Main() method, it calls CreateWebHostBuilder() method passing it the command line arguments. https://github.com/WebHost.cs

As you can see, CreateWebHostBuilder() method returns an object that implements IWebHostBuilder.

On this object, Build() method is called which builds a web host that hosts our asp.net core web application.

On the web host Run() method is called, which runs the web application and it begins listening for incoming HTTP requests.

CreateWebHostBuilder() method calls CreateDefaultBuilder() static method of the WebHost class.

CreateDefaultBuilder() method creates a web host with pre-configured defaults. CreateDefaultBuilder() method does several things to create a web host. 

As part of setting up a web host, Startup class is also configured using the UseStartup() extension method of IWebHostBuilder class.

By convention, the startup class in ASP.NET Core is named Startup. This class has 2 methods.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    { }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

Startup class does the following 2 very important things

  • ConfigureServices() method configures services required by the application
  • Configure() method sets up the application's request processing pipeline


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives