How to add a custom middleware in C#?
Loading
How to add a custom middleware in C#?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Madhu PatelRank #663 · 3.6K reputationPosted May 29, 2025, 7:07 AM EDT
You can read this article:
https://www.c-sharpcorner.com/article/create-a-custom-middleware-in-an-asp-net-core-application/
Sandhiya PriyaRank #26 · 43.2K reputationPosted Oct 27, 2025, 1:30 AM EDT
What is Middleware in ASP.NET Core?
Middleware is a piece of code that processes HTTP requests and responses in a pipeline.
Each middleware can:
Do something before and/or after the next middleware runs.
Either pass the request along or stop it.
In short: Middleware = A request handler that sits in the HTTP pipeline.
Steps to Create and Add Custom Middleware
1. Create a Custom Middleware Class
using Microsoft.AspNetCore.Http; using System.Threading.Tasks; public class MyCustomMiddleware { private readonly RequestDelegate _next; public MyCustomMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { // Code before next middleware Console.WriteLine(" Request incoming: " + context.Request.Path); // Call the next middleware in the pipeline await _next(context); // Code after next middleware Console.WriteLine(" Response outgoing: " + context.Response.StatusCode); } }2. Create an Extension Method (optional but recommended)
using Microsoft.AspNetCore.Builder; public static class MyCustomMiddlewareExtensions { public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware(); } }3. Register Middleware in
Program.csorStartup.csFor .NET 6 / .NET 7 / .NET 8
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseMyCustomMiddleware(); // Custom middleware added here app.MapControllers(); app.Run();For older versions (Startup.cs)
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMyCustomMiddleware(); app.UseMvc(); }4. Run the Application
When you send a request (e.g., to an API endpoint), you’ll see logs like:
Why Use Custom Middleware?
Logging or request tracking, Authentication / Authorization , Exception handling , Request/Response modification ,Performance monitoring
Summary
In Short : Custom Middleware = Your own code logic that runs in the ASP.NET Core request pipeline before or after the main app logic.