HttpContext, Dependency Injection, Request Pipeline, Middleware in ASP.NET Core web apps explained

middleware_di_httpcontext_explained
  • ASP.NET Core is a framework to build web applications that run on .NET runtime
    aspnet%20core%20di%20and%20request%20pipeline%20architecture.png

Web Application

  • An ASP.NET Core web application contains
    • HttpContext object (created per HTTP request)
    • Dependency Injection container (aka DI container)
    • Request pipeline (bunch of middlewares)

HttpContext object

  • 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
    • MapRazorPages - sets up routes for razor pages

References

Comments

Popular posts from this blog

ClaimsPrincipal, ClaimsIdentity, Claims explained in dotnet authentication

Manage packages in dotnet applications

Implicit usings, top level statements, file scoped namespaces in dotnet