Connect with us

What is Middleware?

It is assembled into an app pipeline to handle requests and responses in software. There are two components.

  • It passes the request to the next component in the pipeline.
  • It performs work before the next component.

The request delegates handle each HTTP request. Request delegates are used to request pipeline.

There are three extensions methods Run, Map, and Use is configured in Request delegates. The delegates are specified in delegates to specified in the line as an anonymous method of Single Request and it’s also called in-line middleware, or it is defined in a reusable class. These reusable class and in-line anonymous methods are middleware it’s also called middleware components. The pipeline of request is responsible for instancing the next components in the pipeline or short-circuiting the pipeline of Every Middleware Component.

Create a Middleware Pipeline with IApplicationBuilder

The Request pipeline consists of a sequence of request delegates it’s called one after the other. The following diagram demonstrates the concept, the thread execution follows from Middleware to the response.


Perform each delegate’s operation before and after the next delegate, the pipeline called by Exception Handling. The pipeline can catch exceptions that occur in later stages.

It is a possible simple way in Asp.Net Core set up to a single request delegate that handles all requests. This case doesn’t include an actual request pipeline. Every HTTP request called to a single anonymous function is called to the response.

public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello Core");
});
}

The multiple delegates request together with the Use of Chain. The parameter of next represents the next delegate in the pipeline. The next parameter calling of you can short-circuit the pipeline. You can typically perform actions both before and after the next delegates.

public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
await next.Invoke();
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello 2nd delegate");
});
}

Middleware Order

The complete request processing pipeline Asp.Net Core MVC and Razor Pages apps in the following diagram to be shown. In a typical app, existing Middleware is ordered, and where custom Middleware’s are added where you can see. In existing Middleware’s or inject new custom Middleware’s as necessary for your scenarios to full control over. The Request enters the existing Middleware and custom Middleware and Response returns to existing Middleware and custom Middleware.

  • Request & Response
  • Exception Handler
  • HSTS
  • Https Redirection
  • Static
  • CORS
  • Authentication
  • Authorization
  1. Custom Middleware
    • Custom 1
    • Custom….
  2. Endpoint

The preceding diagram executes the filter pipeline for the corresponding app type like MVC or Razor Pages of the Endpoint Middleware. The MVC Endpoint is also called the Endpoint Middleware.

Catch Exception using a Middleware in ASP.NET core

Catch Exception using a Middleware in ASP.NET core

The Middleware Components are added in the order in the Startup.The configure method defines the order in which the Middleware components are invoked on requests and reverse order for the response. The security, performance, and functionality orders are very critical.

Startup.Configure method added to security-related Middleware components in the following order

public void Configure (IApplicationBuilder app, IWebHostEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDevelopmentExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoint =>
{
endpoint.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

In the above code:

  • When creating a new web app with individual user accounts is commented out so that Middleware is not added.
  • Every Middleware not needs to go in the exact order, but many do.

For Example

  • The orders are must show in UseCors, UseAuthentication, and
  • The UseResponseCaching due to UseCors must before in this bug. 

Middleware component for common app scenarios in the following Startup.Configure method

Error/Exception handling

  • The app runs in the Development environment:
    • The (UseDeveloperExceptionPage) reports app runtime errors in Exception Page Middleware
    • The Middleware reports database runtime errors in Database Error Page.
  • The app runs in a production environment:
    • (UseExceptionHandler) catches exceptions thrown in the following Middlewares.
    • (HSTS) HTTP Strict Transport Security Protocol Middleware (UseHsts) adds the Strict-Transport-Security header.
  1. The UseHttpsRedirection redirects HTTP requests to HTTPS.
  2. The UseStaticFiles return static files and short-circuits further request processing
  3. UseCookiePolicy conforms the app to the EU General Data Protection Regulation (GDPR) regulations.
  4. The UseRouting to a route request.
  5. The UseAuthentication attempt to authenticate the user before they’re allowed access to security resources.
  6. The UseAuthorization authorizes a user to access secure resources.
  7. The UseSession establishes and maintains session state. The app uses the session state, call Session Middleware after Cookie Policy Middleware, and before MVC Middleware.
  8. The UseEndpoints with MapRazorPages to add request pipeline with Razor Pages EndPoints.


public void Configure (IApplicationBuilder app, IWebHostEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDevelopmentExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoint =>
{
endpoint.MapRazorPages();
});
}

Every Middleware extension method is defined on IApplicationBuilder through Microsoft.AspNetCore.Builder namespace.

The First Middleware component adds to the pipeline in UseExceptionHandler. When any exceptions that occur in later calls in Exception Handler Middleware catches.

The Static Files are handled to requests where Middleware of Static Files by Static File Middleware before Response Compression Middleware. It is not compressed with Middleware order. Razor Pages can be compressed.
public void Configure (IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseResponseCompression();
app.UseEndpoints(endpoint =>
{
endpoint.MapRazorPages();
});
}

The UseSpaStaticFiles usually comes last in the Middleware pipeline in SPA Middleware. The SPA means Single Page Applications (SPAs).

  • It allows all other middleware’s to respond to match the requests.
  • The client-Side is allowed to SPAs to run for all routes that are unrecognized by the server app. 

Global Exception Handling with Custom Middleware

You can write a code for Custom Middleware for error handling, and you can access to current HttpContext with error details.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace AspNetCoreWebApplication
{
public class WTRCustomMiddleware
{
private readonly RequestDelegate _next;
public WTRCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await context.Response.WriteAsync("- Before Message - \n\r");
await _next(context); var ex = context.Features.Get();
await context.Response.WriteAsync("\n\r - After Message - ");
}
}
Now create a Middleware Extensions class
public static class WTRCustomMiddlewareExtensions
{
public static IApplicationBuilder UseWTRCustomMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
}

You can call Custom Middleware in configure method of Startup.cs
app.UseWTRCustomMiddleware();
app.Run(async context =>
{
await context.Response.WriteAsync("Welcome to Code!");
});

The catch error status code like page not found, Internal server error you can add in Startup.Configure method.
app.useStatusCodePages();
You get the following error message “Status Code: 404 Not Found”

Conclusion 

So, in this blog we discussed about middleware’s in .NET briefly. Middleware are a piece of code that manages request and responses. You can utilize middleware’s for many conditions, but the most apparent are as exception handlers.


Technocrat and entrepreneur with years of experience building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and have been associated with ASP.NET software development companies.

Continue Reading
Advertisement