Thursday, August 14, 2025

what's Middleware

Thursday, July 10, 2025 6 مشاهدة

know what's Middleware and how we can apply concept in Web Devlopment

Middleware  is code that runs between the incoming HTTP request from the user and the outgoing HTTP response from the server, it acts as a layer that handles things before the request reaches a controller or after the response leaves the controller.

📦 Real-Life Analogy:

Imagine you own a restaurant, and every order goes through:

  • 🛡️ The security guard (checks if the person has a reservation)
  • 🎩 The host (guides them to the table)
  • 📝 The waiter (takes the order)
  • 👨‍🍳 The chef (prepares the meal)
  • 🍽️ The waiter returns with the meal

Each one of these roles represents a Middleware—a layer that processes the request before the final result is served.


Example : Applying middleware pipeline inside Program.cs




MyCustomMiddleware

public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // تنفيذ أي منطق قبل الانتقال للـ Middleware التالي
        Console.WriteLine("طلب جديد وصل!");

        await _next(context); // الاستمرار للـ Middleware التالي

        // تنفيذ أي منطق بعد الاستجابة
        Console.WriteLine("تم إرسال الاستجابة!");
    }
}

then we register Middleware  pipeline in Program.cs

register Middleware pipeline

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseMiddleware<MyCustomMiddleware>(); // تسجيل الـ Middleware

app.MapControllers(); // أو MapGet، حسب نوع التطبيق

app.Run();

Some Common Types of Middleware:

MiddlewareFunctionUseRoutingDefines request routes.UseAuthenticationHandles user sign-in and identity.UseAuthorizationVerifies user permissions.UseStaticFilesServes static files like images, CSS, and JS.UseExceptionHandlerManages global error handling.


Why Do We Use Middleware?

  • To inspect requests before they reach the Controllers
  • To handle application errors
  • To manage authentication (Auth)
  • To write logs
  • To configure CORS or set security headers


 Note

Each middleware in ASP.NET Core runs within a sequential structure called the middleware pipeline.

  • Every middleware executes in order and calls the next one using await _next(context).
  • If a middleware does not call the next one, the pipeline is interrupted and the request won’t reach the controllers. This behavior is called Short-Circuiting.

This gives the application full control over incoming requests and is commonly used for early validation, token checks, or blocking unauthorized access.


💡 Summary:

Middleware is a series of steps or layers that control how the server processes incoming requests.

Each middleware can either pass the request to the next layer or stop it entirely.

It helps you organize your application and gives you full control over the request-response lifecycle.

Tags:

#tag3
Keyboard