
ليه ترتيب الـ middleware مهم؟ إزاي الـ pipeline في ASP.NET Core بيشتغل فعلًا
- كاتب موثّق
- .NET 10
محتويات المقال
app.UseAuthentication()، فلما بيشتغل، محدش يكون قرا الـ token لسه.
الفكرة الغلط الشائعة
Program.cs لستة features بتشغّلها. طالما كل middleware متسجل، ترتيب الـ app.Use... مش مهم، والـ framework هو اللي هيعرف كل واحد يشتغل إمتى.
builder.Services.Add... نادرًا ما بيفرق. وسطور الـ app.MapGet ممكن تتحط تقريبًا في أي حتة في الملف وتشتغل. ولو ما ناديتش UseRouting أو UseAuthentication أو UseAuthorization بنفسك، الـ WebApplication بيضيفهم لك في مكان منطقي. والترتيب الغلط تقريبًا عمره ما بيوقّع التطبيق وهو بيقوم: مفيش exception، بس سلوك فيه حاجة غلط مش باينة.
app.Use... مش settings. كل واحدة بتضيف خطوة في سلسلة، والسلسلة دي بتشتغل بالترتيب اللي انت كتبته بالظبط.
اللي بيحصل فعلًا
الـ pipeline سلسلة calls جوه بعض
HttpContext بتاع الـ request ومعاه delegate اسمه next، وده بيمثّل كل اللي متسجل بعده. الكود اللي قبل await next(context) بيشتغل والـ request داخل، واللي بعده بيشتغل والـ response خارج، بعد ما باقي الـ pipeline يخلص. يعني أول middleware بتسجله بيشوف الـ request الأول والـ response الأخير:
var app = WebApplication.CreateBuilder(args).Build();app.Use(async (context, next) =>{ Console.WriteLine("A: request in"); await next(context); Console.WriteLine("A: response out");});app.Use(async (context, next) =>{ Console.WriteLine("B: request in"); await next(context); Console.WriteLine("B: response out");});app.MapGet("/", () => "Hello"); // endpoints run at the end of the pipelineapp.Run();/ بيطبع "A: request in"، وبعدها "B: request in"، وبعدين "B: response out" و "A: response out". والـ endpoint بيشتغل في النص، مع إن الـ MapGet جاي الأول في الملف: الـ endpoints اللي بتتضاف على الـ WebApplication دايمًا بتتنفذ في آخر الـ pipeline.
الـ middleware بيشوف بس اللي اشتغل قبله
HttpContext. الـ routing هو اللي بيختار الـ endpoint، فالـ endpoint دايمًا null قبل ما الـ routing يشتغل. والـ authentication هو اللي بيقرا الـ token أو الـ cookie ويحط context.User، فأي حاجة بتشتغل قبله بتشوف user مجهول. وده بالظبط bug الـ audit: الـ middleware سأل على الـ user قبل ما حد يبص عليه.
الـ middleware بيحمي بس اللي بعده
فيه middleware بيقفل الـ request بدري
next بيعمل للـ pipeline: الـ static files بترجّع ملف، والـ authorization بيرجّع 401 أو 403. ساعتها مفيش حاجة متسجلة بعده بتشتغل للـ request ده، بينما كل اللي قبله لسه بيشغّل الكود اللي بعد next. وأقصى حالة هي app.Run: الـ delegate بتاعه دايمًا terminal، فأي app.Use مكتوب بعده عمره ما هيشتغل.
الـ audit middleware بعد الـ fix
var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();var app = builder.Build();app.Use(async (context, next) =>{ // runs before authentication: no token has been read yet var user = context.User.Identity?.Name ?? "anonymous"; app.Logger.LogInformation("{User} -> {Path}", user, context.Request.Path); await next(context);});app.UseAuthentication();app.UseAuthorization();app.MapGet("/orders", () => "orders").RequireAuthorization();app.Run();var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();var app = builder.Build();app.UseAuthentication(); // reads the token and sets context.Userapp.Use(async (context, next) =>{ // before authorization, so rejected calls are logged too var user = context.User.Identity?.Name ?? "anonymous"; app.Logger.LogInformation("{User} -> {Path}", user, context.Request.Path); await next(context);});app.UseAuthorization();app.MapGet("/orders", () => "orders").RequireAuthorization();app.Run();/orders بـ token سليم لـ "alice". النسخة الأولى بترد 200 وبتسجّل "anonymous -> /orders". التانية بتسجّل "alice -> /orders". والـ call اللي من غير token بياخد 401 في الاتنين، بس النسخة التانية بتسجّله هو كمان، لأن الـ audit بيشتغل قبل ما الـ authorization يرفض الـ request.
الـ middleware المشهورة مكانها فين
UseExceptionHandler | ||
UseStaticFiles | ||
UseRouting | ||
UseCors | ||
UseAuthentication | context.User | |
UseAuthorization |
تطبقها إزاي في مشروعك
ابدأ من الترتيب اللي في الـ docs رتّب Program.csزي الـ docs: الـ exception handling، وبعده HSTS، والـ HTTPS redirection، والـ static files، والـ routing، والـ CORS، والـ authentication، والـ authorization، والـ middleware بتاعك، وفي الآخر الـ endpoints.حط الـ middleware بتاعك حسب اللي محتاجه لو بيقرا context.User، حطه بعدUseAuthentication. لو بيقرا الـ endpoint، حطه بعد الـ routing. ولو لازم يلف كل حاجة، زي قياس الوقت أو تسجيل الأخطاء، حطه قريب من الأول.اختبر الـ pipeline، مش الـ endpoint بس اكتب integration test بيبعت request حقيقي للتطبيق ويشيّك على النتايج الجانبية، زي سطر الـ audit أو الـ 401، عشان أي تغيير في ترتيب Program.csيوقّع test.انقل الـ middleware اللي بيكبر لـ class حوّل الـ inline middleware لـ class فيها method اسمها InvokeAsyncأول ما يكبر. الـ class دي بتتعمل مرة واحدة وقت الـ startup، فخد الـ scoped services كـ parameters فيInvokeAsync، مش في الـ constructor.
الخلاصة
الـ middleware بيشتغل بترتيب الـ app.Use...مع الـ requests، وبالعكس مع الـ responses.الـ middleware بيشوف بس اللي الـ middleware اللي قبله حطه، زي الـ user أو الـ endpoint، وبيحمي بس اللي بعده. الـ middleware اللي بيعمل short-circuiting بيقفل الـ request، ومفيش حاجة متسجلة بعده بتشتغل. الـ endpoints دايمًا بتشتغل في الآخر، ولما تنادي UseRoutingأوUseAuthenticationبنفسك بتاخد مكانهم التلقائي وتحطهم في المكان اللي تختاره.
التعليقات (0)