When a web application receives a HTTP request, it creates a HttpContext object.
HttpContext object contains all the HTTP related information like HTTP request, HTTP response, session details etc.
All the attributes of a HttpContext object can be found in official docs here
Dependency Injection container (DI container)
It is a collection of classes known Services
Before running the web application, services are added (aka registered) into the web application’s DI container
During registration, the lifetime of a service is declared as one of Transient, Scoped, Singleton
Transient - new service instance created every time
Scoped - service instance created once and reused during a single request processing (example: DbContext, authentication)
Singleton - service instance created once and reused every time (example: logging, email)
While processing the HttpContext, a middleware can access the DI container services if required
DI container services are the features (cross-cutting concerns) that are commonly required in many middlewares like database access, email access etc.
Request pipeline and Middleware
Request pipeline is the flow of HttpContext object through multiple application components (called Middlewares) from request till response.
Middleware is the component that process HttpContext object and passes it to the next middleware in a specified order. Hence the name middleware pipeline.
A middleware can be used for logging, authentication, session management etc.
HttpContext, DI container, Middleware in action
Before the web application is started
Services are registered in the application’s DI container
Middleware is added to the application’s request pipeline
The web application is started, and it listens for HTTP requests
When a HTTP request is received
HttpContext object is created
HttpContext is passed through the middleware in the configured order and then HttpContext is passed back to the first middleware
While processing the HttpContext, a middleware can can access required services from DI container (through constructor)
A middleware can short-circuit the request pipeline by not calling the next middleware (for example, throwing an error)
After the middleware processing is completed, the HttpContext is used to send response to the client
Why use Dependency Injection and Middleware
Each middleware or DI container service can focus on a single concern like logging, authentication etc., (Separation of concerns)
A middleware or DI container service can be reused in multiple projects (Don’t repeat yourself)
Since the application is split into multiple components like middlewares and DI container services, testing can be done easily by creating a test environment containing only required components
Simple Web application code explained
The following code creates and runs a simple razor pages ASP.NET Core web application
var builder = WebApplication.CreateBuilder(args);// Add services to the container.
builder.Services.AddRazorPages();var app = builder.Build();// Add middleware to the HTTP request pipeline.if(!app.Environment.IsDevelopment()){
app.UseExceptionHandler("/Error");// The default HSTS value is 30 days. You may want to change this for production scenarios, see <https://aka.ms/aspnetcore-hsts>.
app.UseHsts();}
app.UseHttpsRedirection();
app.UseRouting();
app.MapStaticAssets();
app.MapRazorPages().WithStaticAssets();
app.Run();
The web application is created with a WebApplicationBuilder (variable named builder)
Services are registered into the application’s DI container while it’s creation
Middlewares like routing, razor pages etc., are added to the middleware pipeline
ASP.NET Core provides a number of bult-in middlewares that can be used. These can be found here
Middlewares (like routing, endpoint execution) and DI services (like logging, configuration access) come with the web application by default
The following services are registered in the DI container
AddRazorPages - adds required services for razor pages middleware
The following middlewares are added to the request pipeline
UseExceptionHandler - show more user-friendly error page with less technical details
UseHsts - adds HSTS headers to the response
UseHttpsRedirection- for redirecting HTTP request to HTTPS
UseRouting - matches requests to endpoints
MapStaticAssets - serves static assets like html, css, js, images etc in the wwwroot folder
claimsprincipal_dotnet Authentication means identifying a subject (user, external application etc) ASP.Net Core Identity is a framework that uses claims based authentication to authenticate users Key concepts in Claims-based authentication Claim Claim is a statement about the subject (user) being authenticated It is a key value pair (like username=John is a claim, email=john1543@gmail.com is a claim, userId=236 is a claim) A claim can have an issuer (for example: userId=236 as per system , date of birth=1st-Jan-2006 as per Gmail ; here system and Gmail are the issuers) ClaimsIdentity ClaimsIdentity is a collection of claims of the subject (user) For example, driving license of a subject (user) can be a ClaimsIdentity that has claims like name, photo, date of birth, address etc. Passport can be a ClaimsIdentity that has claims like name, place of birth, photo, nationality, permanent address etc ClaimsIdentity also has a string property called Authenti...
dotnet_packages By using packages , third party logic can be used in dotnet applications Packages declaration in csproj file The external packages used by a project are declared in its csproj file like the following The packages will be downloaded and linked as per the csproj package references during the restore or build process Browse Nuget packages online Nuget packages can searched online at https://www.nuget.org/PACKAGES Manage packages from dotnet cli Install / update a package command - dotnet add <PROJECT_FOLDER> package <PACKAGE_NAME> -v <VERSION> The following command adds/updates a package in a project. If the package is already present, it will be updated to the latest version dotnet add package Microsoft.Data.Sqlite Install a specific version using -v flag like the following dotnet add package Microsoft.Data.Sqlite -v 8.0.10 List all packages in a project command - dotnet list <PROJECT_FOLDER> package ...
implicit usings Implicit usings = no repeated using statement in all files With implicit usings feature in a C# project, common using statements are automatically added by the compiler in all the C# files. For example using System; statement is not required to run the dotnet console application as shown below Console . WriteLine ( "Hello World!" ) ; Additional implicit usings can be declared in a C# project with global usings statements in any one of the project’s C# files as shown below. global using Ardalis . GuardClauses ; global using MediatR ; global using Project2 . Utils ; Existing implicit usings can be removed or included in the .csproj file of the C# project as shown below < ItemGroup > < Using Remove = " System.Threading.Tasks " /> < Using Include = " System.Math " /> </ ItemGroup > The implicit usings added in a C# project is based on the project type as sh...
Comments
Post a Comment