Middileware is a piece of code that is used in application pipeline for processing the input requests and respective responses. Middilewares are built-in components in .Net Core or we can create custom middilewares based on our requirements. Middilewares are mostly written in classes and used as an extension methods. Request Delegates are used to build the request pipeline.
Problem Defination :- To implement Custom Middileware in ASP.Net core we have a requirement in which when we hit a url("/Home/Index") then it should not hit and it should be redirected to other url("/home/CustomError") page using the Custom Middileware.
In the below Image you can see the url in which Home is the controller and Index is the action method and when we hit this url it will show the index page.
After implement the Middileware it will redirect to Home/Customerror page when we hit the above url.
Create a class named it CheckUrlValidations and create a constructor in this class and assign the Properties for RequestDelegate and write the method InvokeAsync in which specify the logic for Url checking and after it create a extension method UseCheckUrlValidations as like the below image and code written into the below code block.
public class CheckUrlValidations
{
public readonly RequestDelegate RequestDelegate;
public CheckUrlValidations(RequestDelegate requestDelegate)
{
RequestDelegate = requestDelegate;
}
public async Task InvokeAsync(HttpContext context)
{
var cultureQuery = context.Request.Path.Equals("/Home/Index");
if(cultureQuery)
{
context.Response.Redirect("/Home/CustomError");
}
await RequestDelegate(context);
}
}
public static class CheckUrlValidationsExtensions
{
public static IApplicationBuilder UseCheckUrlValidations(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
Now use this Custom Middile ware in the Program.cs file as shown in below image and below code block.
using MiddileWareExample.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseCheckUrlValidations();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Privacy}/{id?}");
app.Run();
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.