📘 C# Blog Series – Blog 28 **“C# Middleware — Request को Pipeline तरीक़े से कैसे Process करते हैं?

📘 C# Blog Series – Blog 28

**“C# Middleware — Request को Pipeline तरीक़े से कैसे Process करते हैं?






(Real-Life Example: API में Authentication, Logging, Rate-Limiting)”**

C# (ASP.NET Core) में Middleware वो system है जो हर incoming request को
pipeline के अंदर step-by-step process करता है।

अगर आप API, GPS backend, billing system, school ERP, या किसी भी web service पर काम कर रहे हो —
तो middleware सबसे important architecture feature है।

GPS/Web APIs में middleware use होता है:

  • Authentication

  • Logging

  • Exception handling

  • Token validation

  • Rate-limiting

  • Request/response modification

  • Restricting access

  • Maintenance mode

आज इसे super easy तरीके + real-life examples के साथ समझेंगे।


🟦 1. Middleware क्या होता है? (Simple Definition)

Middleware =
एक ऐसा component जो request को intercept करता है और फिर आगे भेजता है।

मतलब request API controller तक पहुँचने से पहले कई checkpoints से गुजरती है।

Pipeline की तरह:

Request → [Middleware 1][Middleware 2][Middleware 3] → Controller

🟢 2. Middleware Pipeline कैसे बनता है?

Program.cs में order define होता है:

app.UseMiddleware<LoggingMiddleware>(); app.UseMiddleware<AuthMiddleware>(); app.UseMiddleware<RateLimitMiddleware>();

Order = बहुत important
Top to bottom execute होता है।


3. Custom Middleware कैसे बनाते हैं?

public class LoggingMiddleware { private readonly RequestDelegate _next; public LoggingMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { Console.WriteLine("Request: " + context.Request.Path); await _next(context); // next middleware को call } }

Use:

app.UseMiddleware<LoggingMiddleware>();

🌟 4. Real-Life GPS Example: API Logging Middleware

हर API request को log करना बहुत जरूरी है।

public async Task Invoke(HttpContext context) { Console.WriteLine($"[{DateTime.Now}] {context.Request.Method} {context.Request.Path}"); await _next(context); }

अब हर hit record हो रही है।


5. Authentication Middleware (Token Validation)

public async Task Invoke(HttpContext ctx) { if(!ctx.Request.Headers.ContainsKey("token")) { ctx.Response.StatusCode = 401; await ctx.Response.WriteAsync("Token Missing"); return; } await _next(ctx); }

अब बिना token → कोई API access नहीं।


6. Real-Life: GPS Admin Panel में Role-Based Access

if (!ctx.User.IsInRole("Admin")) { ctx.Response.StatusCode = 403; return; }

अब केवल admin कुछ APIs access कर सकता है।


7. Exception Handling Middleware (Must Have)

API crash होने से बचाता है।

try { await _next(ctx); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); ctx.Response.StatusCode = 500; }

GPS server में यह बेहद ज़रूरी है।


🟠 8. Rate-Limiting Middleware (Protect Server)

अगर कोई client बहुत अधिक requests भेज रहा हो → block करो।

if (TooManyRequests(ip)) { ctx.Response.StatusCode = 429; await ctx.Response.WriteAsync("Slow down!"); return; }

DDOS और API abuse रोकने में perfect।


🔵 9. Maintenance Mode Middleware

if (_settings.IsMaintenance) { ctx.Response.StatusCode = 503; await ctx.Response.WriteAsync("Server under maintenance"); return; }

एक click में पूरा API बंद/चालू।


🟣 10. Real GPS Use: API Key Middleware

हर request में API Key check:

string key = ctx.Request.Headers["API-Key"]; if (key != _settings.ValidKey) { ctx.Response.StatusCode = 401; return; }

🧠 11. Middleware का सबसे बड़ा फायदा? — Centralized Logic

✔ दुबारा code नहीं लिखना पड़ता
✔ हर API route पर same security
✔ Logging हर जगह working
✔ Exception handling uniform
✔ Config change आसान

GPS backend में यह architecture must-have है।


🔚 Conclusion

C# Middleware आपके application को बनाता है:

✔ Secure
✔ Organized
✔ Maintainable
✔ Scalable
✔ Professional
✔ Production-ready

API development हो या GPS tracking server —
Middleware clean architecture का backbone है।

Post a Comment

0 Comments

Translate

Close Menu