
الـ parameter ده جه منين؟ الـ parameter binding في Minimal APIs
- كاتب موثّق
- .NET 10
محتويات المقال
{id} لـ {orderId} عشان يبان أوضح في الـ OpenAPI document. الـ handler لسه مكتوب فيه int id. الـ build نضيف، ومفيش analyzer اشتكى، وفي الـ production بقى GET /orders/42 بيرد 400 والـ body فاضي. وعلى الـ log level العادي، مفيش ولا سطر. الـ parameter ما اختفاش: هو بس اتنقل في صمت من الـ route للـ query string، المكان اللي محدش بيبعته فيه.
الفكرة الغلط الشائعة
[FromQuery] و [FromBody] و [AsParameters] موجودة عشان القراية أو الـ documentation، ولو شيلتها مفيش حاجة هتتغير.
(int id) مع route زي /orders/{id} بيقرا من الـ route. والـ (Order order) في POST بيقرا الـ JSON body. والـ service المتسجلة بتوصل من الـ من غير أي attribute. والأمثلة الرسمية نادرًا ما بتستخدم attributes، فسهل تستنتج إن الـ framework ذكي كفاية إنه يعرف كل مرة.
اللي بيحصل فعلًا
القواعد بالترتيب
attribute صريح: [FromRoute]أو[FromQuery]أو[FromHeader]أو[FromBody]أو[FromForm]أو[FromServices]أو[AsParameters].نوع خاص: HttpContextأوHttpRequestأوHttpResponseأوClaimsPrincipalأوCancellationTokenأو نوع من أنواع الـ form والملفات أوStreamأوPipeReader.نوع فيه static method اسمها BindAsync.stringأو نوع فيه static method اسمهاTryParseزيintأوGuid: من الـ route لو اسمه موجود في الـ route template، وإلا من الـ query string.نوع متسجل كـ service: من الـ dependency injection. أي حاجة تانية: من الـ request body.
الاسم هو العقد
{id} لـ {orderId}، وساعتها int id مش هيلاقي اسمه، فبيتقري من ?id=. والـ parameters كلها required إلا لو nullable أو ليها default value، فأي request من غير ?id= بيفشل برسالة "Required parameter "int id" was not provided from query string.". في الـ Development، ده بيطلع BadHttpRequestException على الـ developer exception page. وفي أي environment تاني، الـ ThrowOnBadRequest بيبقى مقفول: الـ client بياخد 400 والـ body فاضي، والسبب بيتسجل على مستوى Debug بس.
الـ headers عمرها ما بتتخمّن
string apiKey واللي كان المفروض ييجي من الـ header X-Api-Key بيتقري من ?apiKey=. الـ clients اللي بتبعت الـ header بتاخد 400، والـ "حل" اللي حد هيلاقيه في الآخر إنه يحط الـ key في الـ URL، فيلاقي نفسه في الـ access logs وفي الـ browser history.
الـ complex types بتقع في الـ body
OrderQuery(string? Status, int Page) مفيهوش TryParse ومش service، فبيوصل للقاعدة رقم 6: الـ body. بس الـ GET والـ HEAD والـ OPTIONS والـ DELETE مش بيعملوا binding من الـ body لوحدهم، فالـ endpoint مش بيعرف يتبني: "Body was inferred but the method does not allow inferred body parameters.". والـ service اللي نسيت تسجلها بتقع بنفس الطريقة، لأنها مجرد type الـ container مايعرفهوش.
[AsParameters] هو اللي بتطلب بيه ده.
الـ orders endpoints بعد الـ fix
var builder = WebApplication.CreateBuilder(args);var app = builder.Build();// {orderId} in the route, id in the handler: id is read from ?id=app.MapGet("/orders/{orderId:int}", (int id) => $"Order {id}");// headers are never inferred: apiKey is read from ?apiKey=app.MapGet("/reports", (string apiKey) => "report");// a record isn't read from the query string: it's inferred as the bodyapp.MapGet("/orders", (OrderQuery query) => query);app.Run();public record OrderQuery(string? Status, int Page = 1);using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);var app = builder.Build();app.MapGet("/orders/{orderId:int}", (int orderId) => $"Order {orderId}");app.MapGet("/reports", ([FromHeader(Name = "X-Api-Key")] string apiKey) => "report");// each property binds by the usual rules: Status and Page from the queryapp.MapGet("/orders", ([AsParameters] OrderQuery query) => query);app.Run();public record OrderQuery(string? Status, int Page = 1);/orders مش بيعرف يتبني. اعمل comment للـ endpoint ده، وبرّه الـ Development هتلاقي /orders/5 بيرد 400 فاضي، ونفس الكلام لـ /reports حتى والـ header متبعت. النسخة التانية بترد Order 5، وبترجّع {"status":"open","page":2} لـ /orders?status=open&page=2، وبترجع لـ page 1 لو page مش موجودة، ولسه بترفض ?page=two بـ 400.
اللي كتبته vs اللي بيحصله binding
int id مع route فيه {orderId} | ?id= | |
string apiKey والمقصود header | ?apiKey= | |
OrderQuery query في GET | ||
[AsParameters] OrderQuery query |
تطبقها إزاي في مشروعك
طابق أسامي الـ route وانت قاصد لكل {name}في الـ route template، اتأكد إن فيه parameter في الـ handler بنفس الاسم بالظبط، أو بيستخدم[FromRoute(Name = ...)]. واعمل نفس المراجعة كل ما حد يغيّر اسم route.علّم الـ headers والـ forms والـ body في الـ GET استخدم [FromHeader]لأي حاجة جاية من header، و[FromForm]للـ form posts، و[FromBody]لو GET أو DELETE لازم يقرا body فعلًا. ولا واحدة من دول بتتخمّن لوحدها.استخدم AsParameters للـ filter objects لما GET ياخد كذا قيمة من الـ query، جمّعهم في record وعلّم الـ parameter بـ [AsParameters]. ده بيعمل binding لكل property بالقواعد العادية، ومش recursive model binding، فخلّي الـ record بسيط من غير nesting.ابعت request واحد في الـ tests أي integration test بيبعت request للتطبيق بيبني كل الـ endpoints، فالـ parameter اللي القواعد مش عارفة تحطه بيوقّع الـ test بدل ما يوقّع أول call في الـ production.
الخلاصة
الـ Minimal APIs بتعمل binding للـ parameters بلستة قواعد مترتبة: attribute، نوع خاص، BindAsync، route أو query للأنواع البسيطة، services، وفي الآخر الـ body.الـ parameter البسيط بيتقري من الـ route بس لو اسمه مطابق للـ template، وإلا بيتقري من الـ query string. الـ headers والـ forms عمرها ما بتتخمّن، والـ complex types بتقع في الـ body، والـ GET والـ DELETE مش بيسمحوا بيه لوحدهم. غلطة الـ binding بتظهر وقت التشغيل، 400 فاضي أو 500 على كل الـ endpoints، فالـ [FromHeader]والـ[AsParameters]سلوك، مش ديكور.
التعليقات (0)