ASP.NET Core Middleware

Search for a command to run...

No comments yet. Be the first to comment.
In this series, I will write about advance concepts of ASP.NET Core. This includes following topics - DI - Middleware - Filters - Request processing pipeline - Logging, Exception Handling
In ASP.NET core world , a user request is routed to appropriate controller and then action method to be executed. In some cases, user may need to run some code before or after during execution pipeline. Filters allows some code to run before and afte...
ASP.NET Core Configuration Guide Overview ASP.NET Core uses a layered configuration system where later sources override earlier ones for the same key. Configuration Priority Order Priority Source
Legacy Delphi applications often struggle with outdated UI/UX, performance issues, and monolithic architectures that make refactoring difficult. However, a full rewrite is not always feasible due to time, cost, and the risk of disrupting critical bus...
Entity Framework Core (EF Core) is a powerful and flexible object-relational mapping (ORM) framework for .NET applications, enabling developers to work with relational databases using strongly-typed .NET objects. It simplifies data access by abstract...

In this article we are going to cover some advance scenarios where Options pattern is very useful. We have covered the basic understanding of Options pattern into Options pattern in ASP.NET Core: Introduction article. Please go through it if not fami...

In this article we will learn about Options pattern in ASP.NET Core for dealing with application configurations. The Options pattern uses the C# classes to access and manage the configurations thus providing more flexibility and type safe approach to...

An ASP.NET Core application's workflow consist of accepting request and serving response to client. With this workflow, an application has different features / functionality like authentication, error handling or logging etc. ASP.NET Core has provided concept of middleware to implement application's features. A middleware is nothing but a C# class which is placed inside ASP.NET Core's request processing pipeline.
A middleware can perform below tasks :
Middleware components are configured in Configure method of Startup.cs file. ASP.NET Core has provided some built-in middleware. Middleware can also be added via Nuget package manager or custom middleware can be added.
Below is the Startup.cs file's Configure method. All the middleware shown in this file are built-in middleware
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/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.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
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.

Inline middleware can be added using app.use or app.Run method.
Middleware defined using app.Use may call next middleware component in the pipeline. Middlware defined using app.Run will never call subsequent middleware.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware 1 using app.Use()");
await next();
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware 2 using app.Use()");
await next();
});
app.Run(async context =>
{
await context.Response.WriteAsync("Middleware 3 using app.Run()");
// Short circuiting the pipeline
});
// This will never be called
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware 4 using app.Use()");
await next();
});
}

below is an example where a middleware is created to log the incoming request's http method
public class LogRequestMethodMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<LogRequestMethodMiddleware> _logger;
public LogRequestMethodMiddleware(RequestDelegate next,
ILogger<LogRequestMethodMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync (HttpContext context)
{
_logger.LogInformation(context.Request.Method);
await _next(context);
}
}
Inside Startup.cs file
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<LogRequestMethodMiddleware>();
app.Run(async context =>
{
await context.Response.WriteAsync("\n Adding custom middleware");
});
}
ASP.NET Core has some built-in middleware for common application scenario :