Endpoint-centric Architecture
FastEndpoints framework مبني حول فكرة إن كل endpoint class يضم تعريف الـ route والـ request/response types والـ handler والـ validation والـ authorization metadata. ده يختلف عن controller يجمع عدة actions. هو طبقة framework إضافية فوق ASP.NET Core؛ اتعلم مبادئ HTTP و DI و validation أولاً ثم قيّم هل التنظيم ده يناسب الفريق.
public sealed class GetProductRequest
{
public int Id { get; set; }
}
public sealed record GetProductResponse(int Id, string Name);
public sealed class GetProductEndpoint : Endpoint<GetProductRequest, GetProductResponse>
{
private readonly IProductService _service;
public GetProductEndpoint(IProductService service) => _service = service;
public override void Configure()
{
Get("/api/products/{id}");
AllowAnonymous();
Description(b => b.WithSummary("Find a product by id"));
}
public override async Task HandleAsync(
GetProductRequest req, CancellationToken ct)
{
var product = await _service.FindAsync(req.Id, ct);
if (product is null) { await SendNotFoundAsync(ct); return; }
await SendOkAsync(new(product.Id, product.Name), ct);
}
}تأكد من version-specific APIs عند تثبيت package؛ المثال يوضح الشكل العام المعروف، وقد تتغير overloads والـ namespaces بين الإصدارات.
Lifecycle: من Request DTO إلى Endpoint Handler
FastEndpoints مكتبة خارجية فوق ASP.NET Core تقدم endpoint-centric structure: كل use case غالباً له endpoint class، request DTO، response DTO، validator، و handler. الفكرة أن route/verb/auth/validation/handler metadata تبقى قريبة من بعضها بدلاً من controller كبير فيه actions كثيرة. ده convention framework؛ لازم تقرأ docs الخاصة بإصداره قبل اعتماد APIs لأن package surface قد يتغير.
public sealed class GetProductEndpoint(IProductQuery query)
: Endpoint<GetProductRequest, ProductResponse>
{
public override void Configure()
{
Get("/api/products/{id}");
AllowAnonymous();
Description(x => x.WithTags("Products"));
}
public override async Task HandleAsync(
GetProductRequest request, CancellationToken ct)
{
var product = await query.FindAsync(request.Id, ct);
if (product is null)
{
await SendNotFoundAsync(ct);
return;
}
await SendOkAsync(product, ct);
}
}
public sealed class GetProductRequest
{
public int Id { get; set; }
}الـ endpoint class ليس مكاناً تلقائياً لكل business logic. inject application service/query handler، ثم حول النتيجة إلى HTTP response. خلي قواعد domain في domain/application، وليس في framework endpoint class.
Handler Responsibility و Response Semantics
Endpoint class تستقبل request وتنسق use case، لكنها لا ينبغي أن تحتوي كل business rules. حقن application service، نفّذ operation، ثم أرسل status/response مناسباً. لا تجعل كل failures ترجع 200 مع { success:false }؛ استخدم HTTP semantics الصحيحة مثل 404/409/422 حسب contract. وثّق response types في OpenAPI metadata.
Request DTO منفصل عن domain entity، و response DTO منفصل عن persistence model. لو endpoint يحتاج current user، استخرج claims من context عبر framework-supported APIs ثم مرر user identity إلى use case. لا تجعل business service تعتمد مباشرة على Hub/HttpContext/Endpoint framework.
Request Flow و DTO Boundaries
النمط المعتاد: framework يطابق route/verb، يعمل binding للـ request DTO، يشغّل validators، يجهز DI dependencies، ثم ينفذ endpoint handler، وبعدها يكتب response. افهم lifecycle الفعلي للنسخة المستخدمة لأن validation/serialization hooks قد تختلف. لا تخلط request DTO مع entity، ولا تجعل endpoint handler يحمل database transaction طويلة من غير application service boundary.
في use case فيه expected errors، رجّع HTTP status مناسباً و Problem Details contract consistent. لا تستخدم framework-specific send helper كأنه business outcome؛ هو مجرد HTTP adapter.
REPR في رسمة: Request → Endpoint → Response
تسجيل FastEndpoints داخل ASP.NET Core
بعد إضافة package المتوافقة مع target framework، سجّل framework services ثم فعّل endpoints في pipeline. التسجيل لا يحوّل Controllers/Minimal APIs تلقائياً؛ أنت تختار أي endpoint style تستخدمه.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFastEndpoints();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseFastEndpoints();
app.Run();الترتيب هنا يفترض إعداد authentication schemes/policies في services قبل Build. أضف OpenAPI integration وفق الحزمة/الإصدار الذي تختاره، واختبر metadata/security behavior؛ لا تفترض أن وجود route يكفي لتوثيقه أو حمايته.
Validation و DI و Authorization
FastEndpoints يعتمد FluentValidation style في request validators، ويقدم اكتشافاً/تسجيل validators عبر framework. القواعد تكون قريبة من endpoint request لكن لا تضع business invariants التي تتطلب domain knowledge داخل validator فقط. خدمات handlers تحقن عبر constructor/DI أو APIs framework المتاحة؛ استخدم lifetimes صحيحة كما في درس DI. Authorization يضبط في Configure عبر AllowAnonymous أو policies/roles حسب الإصدار.
public sealed class CreateProductRequest
{
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
public sealed class CreateProductValidator : Validator<CreateProductRequest>
{
public CreateProductValidator()
{
RuleFor(x => x.Name).NotEmpty().MaximumLength(120);
RuleFor(x => x.Price).GreaterThan(0);
}
}Validation و DI و Authorization
FastEndpoints يدعم validators بأسلوب FluentValidation في كثير من السيناريوهات، ويشغل validation ضمن endpoint pipeline. ده يساعد على إبقاء request rules بجوار request DTO. لكن async validation التي تذهب إلى DB تحتاج مراجعة version/integration behavior و cancellation، كما أن business invariants النهائية يجب أن تظل محمية في domain و database.
public sealed class CreateProductValidator : Validator<CreateProductRequest>
{
public CreateProductValidator()
{
RuleFor(x => x.Name).NotEmpty().MaximumLength(120);
RuleFor(x => x.Price).GreaterThan(0);
}
}Authorization يمكن أن تكون anonymous أو authenticated أو policy/role-based. لا تخلط AllowAnonymous مع مجرد إخفاء endpoint من Swagger. تأكد من إعداد authentication/authorization middleware في ASP.NET Core host، ثم اختبر 401 و403 من HTTP boundary.
Error Responses و Validation Consistency
تأكد من أن validation failures في FastEndpoints تتبع نفس API error contract الذي تستخدمه controllers/Minimal APIs، خصوصاً لو نفس host يحتوي أكثر من style. client لا ينبغي أن يتعامل مع ثلاثة أشكال مختلفة للأخطاء بسبب framework choice. حدد response DTOs و Problem Details policy مشتركة، واختبرها.
Endpoint class هي HTTP adapter؛ application service لا تعتمد على FastEndpoints types. ده يجعل migration أو إعادة استخدام use case أسهل، ويمنع framework-specific response helpers من التسرب إلى business logic.
Grouping و Testing
يمكنك تجميع endpoints حسب feature أو route prefix أو tags، وتطبيق common configuration من base endpoint أو configurator عند الحاجة. احذر من inheritance frameworks داخل framework إذا أصبحت قواعد التنفيذ صعبة التتبع. للاختبار، استخدم unit tests للـ domain/application services، و integration tests عبر WebApplicationFactory للتحقق من route registration و serialization و auth/validation pipeline.
[Fact]
public async Task Invalid_create_request_returns_validation_error()
{
using var client = _factory.CreateClient();
using var response = await client.PostAsJsonAsync("/api/products",
new { name = "", price = -2 });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}Groups و Versioning و Testing
لما عدد endpoints يكبر، نظّمها حسب feature أو bounded context، واستخدم endpoint groups/summary/tags/versioning وفق capabilities المكتبة. حافظ على أسماء واضحة و DTOs صغيرة. لا تجعل كل endpoint يعتمد على generic base class ضخمة تخفي lifecycle؛ abstraction لازم تقلل duplication من غير ما تمنع قراءة behavior.
اختبر validator منفصلاً، واختبر HTTP behavior باستخدام integration testing. اختبر route، serialization، auth policy، validation failure، not found، success، و unexpected exception. الـ library قد توفر test helpers؛ استخدم docs للإصدار الفعلي بدلاً من نسخ API من إصدار مختلف.
Endpoint Testing و Feature Structure
في FastEndpoints، endpoint-per-use-case يساعدك تلاقي مكان behavior بسرعة، لكن كثرة classes قد تتحول إلى boilerplate لو كل endpoint trivial. اجمع request/response/validator بجوار endpoint أو في feature folder حسب convention الفريق. اختبر validation و auth و status code من HTTP، واختبر application service في unit tests منفصلة.
عند استخدام test helpers الخاصة بالمكتبة، راجع package version و docs لأن helpers والـ fixture APIs قد تتغير. لو التطبيق يستخدم custom auth أو DB container، جهز test host بنفس middleware registrations المهمة. لا تجعل test endpoint يتخطى validation أو authorization ثم تعتبر النتيجة ممثلة للإنتاج.
OpenAPI و Versioning داخل FastEndpoints
Endpoint-based libraries غالباً توفر APIs لوصف summary/tags/response types/security metadata. استغلها لتوليد OpenAPI document مفيد. لا تكتفِ باسم class كـ documentation. اكتب request/response schema و examples/status codes، وراجع document الناتج. لو تستخدم versioning، وضح هل version في route أو metadata وكيف يتولد document لكل version.
لو المشروع يستهلك OpenAPI clients، أي تغيير في schema/operation IDs قد يؤثر على generated SDK. راجع compatibility قبل ترقية library أو تعديل naming conventions.
FastEndpoints vs Controllers vs Minimal APIs
| Approach | Strength | Cost / Caution |
|---|---|---|
| Controllers | Mature MVC ecosystem, filters/model binding extensibility, familiar conventions | Can become large controllers; ceremony |
| Minimal APIs | Built-in, lean, first-party, flexible route groups | Needs deliberate organization as endpoint count grows |
| FastEndpoints | Strong endpoint cohesion, built-in validation conventions | Third-party dependency and its conventions/versioning |
لا تختار framework بالـ benchmark headline وحده. قارن maintainability، debugging, DI integration، OpenAPI support، testing، team familiarity، release cadence، compatibility مع .NET target. لو احتياجك يكتمل بـ Minimal APIs، تجنب إضافة abstraction/framework layer بلا قيمة واضحة.
FastEndpoints ولا Controllers ولا Minimal APIs؟
| Approach | Strength | Trade-off |
|---|---|---|
| Controllers | Mature conventions, filters, familiar MVC model | Controllers can become large without feature discipline |
| Minimal APIs | Built-in, low ceremony, direct endpoint composition | Requires deliberate organization as endpoints grow |
| FastEndpoints | Strong endpoint-per-use-case conventions | External dependency and framework-specific conventions |
لا تختار مكتبة لأن شكل الكود أقصر فقط. قيّم ecosystem، compatibility مع .NET target، docs، testability، OpenAPI generation، team familiarity، upgrade cadence، migration cost، واحتياجك الحقيقي. في Junior .NET roadmap، افهم pattern والقراءة العملية، لكن core ASP.NET Core controllers/minimal APIs أعلى أولوية من mastery مكتبة اختيارية.
Adoption Checklist و Version Compatibility
قبل اعتماد FastEndpoints على مستوى solution، تحقق من target frameworks المدعومة، إصدار package، transitive dependencies، طريقة OpenAPI generation، auth integrations، DI activation، testing hooks، release notes، license، ومدى سهولة debugging في IDE. جرّب endpoint representative فيه request DTO و validator و auth policy و integration test بدلاً من benchmark سريع فقط.
لا تخلط FastEndpoints مع minimal route handlers بلا حدود. اختر convention واحدة للـ feature set لتقليل mental model. يمكن أن تتعايش Controllers و Minimal APIs و FastEndpoints في مشروع واحد تقنياً، لكن ذلك قد يربك الفريق إذا لم يكن هناك standard واضح.
Package Compatibility و Adoption Checklist
قبل إدخال FastEndpoints في تطبيق قائم، تحقق من دعم target framework، توافق package مع ASP.NET Core version، OpenAPI integration، auth policies، DI behavior، test utilities، serialization conventions، و migration path. اعمل spike صغير مع endpoint واحد واختبر build/deploy/observability، ثم قرر. لا تنقل كل controllers مرة واحدة لمجرد تفضيل شكل endpoint classes.
في المقابلات، اشرح pattern الأساسي ومقارنته بالـ built-in controllers و Minimal APIs. الأولوية التعليمية تظل لفهم ASP.NET Core fundamentals؛ framework إضافي لا يعوض فهم middleware، DI، routing، HTTP semantics، validation، auth، و testing.
FastEndpoints Review Checklist
قبل اختيارها، اسأل: هل الفريق يعرف ASP.NET Core fundamentals؟ هل package متوافقة مع runtime؟ هل OpenAPI generation يلبي الحاجة؟ هل validators تعمل كما تتوقع؟ هل auth policies متكاملة؟ هل tests سهلة؟ هل migration من controllers ممكنة تدريجياً؟ هل conventions قابلة للفهم عند debugging؟
الهدف من endpoint-centric architecture هو locality: route/request/validator/handler قريبين من بعض. لو أضفت layers كثيرة أو generic base classes غامضة، تفقد الفائدة. خلي endpoint adapter صغيراً، و business logic خارج framework.
Adoption تدريجياً داخل API موجودة
لو عندك controllers قائمة، ممكن تدرس إضافة FastEndpoints تدريجياً على feature جديدة بدلاً من rewrite شامل. لكن وحّد JSON options، Problem Details، auth policies، OpenAPI documents، logging، و testing conventions حتى لا يرى client API مختلفة حسب framework المستخدم داخلياً.
حدد ownership لكل route، وتجنب duplicate route templates بين controllers و FastEndpoints. اختبر startup endpoint discovery و versioning و route conflicts. وثّق في team standards متى تستخدم كل approach؛ وجود ثلاثة styles في نفس codebase بدون قاعدة قرار يرفع cognitive load.
المستوى المطلوب من FastEndpoints
المطلوب في هذا المسار إنك تفهم endpoint-per-use-case، request/response DTOs، handler، validator، DI، authorization، grouping، OpenAPI، والاختبار. تعرف تقرأ endpoint class وتشرح أين تنفذ business logic، وتقدر تقارنها بـ Controller و Minimal API. لا تحتاج تحفظ كل extension method أو تبني framework داخلي؛ المكتبة اختيارية وأولوية تعلمها أقل من built-in ASP.NET Core.
مثال كامل: feature بـ FastEndpoints من الـ request للـ test
FastEndpoints بيطبّق نمط REPR (Request–Endpoint–Response): كل endpoint class لوحدها فيها الـ route والـ auth والـ handler، والـ request/response DTOs جنبها. المثال ده بيجمع كل اللي اتشرح فوق في feature واحدة.
public sealed record CreateInvoiceRequest(Guid CustomerId, List<InvoiceLine> Lines, string Currency);
public sealed record InvoiceLine(string Description, int Quantity, decimal UnitPrice);
public sealed record CreateInvoiceResponse(Guid Id, decimal Total, string Number);
public sealed class CreateInvoiceValidator : Validator<CreateInvoiceRequest> // FluentValidation under the hood
{
public CreateInvoiceValidator()
{
RuleFor(x => x.CustomerId).NotEmpty();
RuleFor(x => x.Currency).Must(c => c is "EGP" or "USD" or "EUR").WithMessage("Unsupported currency");
RuleFor(x => x.Lines).NotEmpty();
RuleForEach(x => x.Lines).ChildRules(l =>
{
l.RuleFor(i => i.Quantity).InclusiveBetween(1, 10_000);
l.RuleFor(i => i.UnitPrice).GreaterThanOrEqualTo(0);
});
}
}
public sealed class CreateInvoiceEndpoint(AppDb db, ITenantContext tenant, IInvoiceNumbering numbering)
: Endpoint<CreateInvoiceRequest, CreateInvoiceResponse>
{
public override void Configure()
{
Post("/invoices");
Policies("invoices:write"); // ASP.NET Core authorization policy
Description(d => d.Produces(409).WithTags("Invoices"));
}
public override async Task HandleAsync(CreateInvoiceRequest req, CancellationToken ct)
{
var customer = await db.Customers.FindAsync([req.CustomerId], ct);
if (customer is null) { AddError(r => r.CustomerId, "Customer not found"); ThrowIfAnyErrors(); }
var invoice = Invoice.Create(tenant.TenantId, customer!, req.Currency,
req.Lines.Select(l => (l.Description, l.Quantity, l.UnitPrice)), await numbering.NextAsync(ct));
db.Invoices.Add(invoice);
await db.SaveChangesAsync(ct);
await Send.CreatedAtAsync<GetInvoiceEndpoint>(new { id = invoice.Id },
new(invoice.Id, invoice.Total, invoice.Number), cancellation: ct);
}
}الـ API الخاصة بإرسال الردود اتغيرت بين نسخ FastEndpoints (مثلًا SendCreatedAtAsync في نسخ أقدم مقابل Send.CreatedAtAsync في الأحدث). راجع الـ docs للنسخة اللي بتستخدمها — reviewed 2026-11-18.
public sealed class CreateInvoiceTests(AppFixture app) : TestBase<AppFixture>
{
[Fact]
public async Task Rejects_unknown_currency_with_400()
{
var (rsp, problem) = await app.Client.POSTAsync<CreateInvoiceEndpoint, CreateInvoiceRequest, ProblemDetails>(
new(Guid.NewGuid(), [new("Consulting", 1, 100)], "XYZ"));
rsp.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
problem.Errors.ShouldContain(e => e.Name == "currency");
}
}قرار الاختيار بالأرقام والفريق
| المعيار | Controllers | Minimal APIs | FastEndpoints |
|---|---|---|---|
| مدعوم رسميًا من Microsoft | نعم | نعم | لا — مكتبة مجتمع (open source) |
| Structure جاهز لكل endpoint | Controller لكل resource | انت بتصممه | class لكل endpoint (REPR) |
| Validation | [ApiController] + DataAnnotations | مدمج من .NET 10 | FluentValidation مدمج |
| Onboarding | الأسهل (معروف للكل) | سهل | محتاج تعلم conventions المكتبة |
| خطر طويل المدى | منخفض | منخفض | dependency على maintainers؛ breaking changes بين majors |
التوصية العملية للـ Junior: اتقن Minimal APIs و Controllers الأول (هتلاقيهم في أي شركة)، واعرف FastEndpoints كنمط تنظيم (REPR/vertical slices) — نفس الفكرة ممكن تطبقها بـ Minimal APIs زي ما في Minimal APIs. اختيار مكتبة زي دي في مشروع شركة قرار يستاهل ADR: مين هيصونه، وخطة لو المكتبة وقفت.
Knowledge check
فريق عنده 300 endpoint بـ Controllers شغالة كويس. حد اقترح migration كاملة لـ FastEndpoints. أحسن رد؟
أخطاء شائعة في FastEndpoints
- endpoint class بقت مكان كل الـ logic لحد ما توصل 400 سطر: الـ domain logic مكانه الـ domain/application.
- خلط conventions بين Controllers و FastEndpoints في نفس الـ API من غير قواعد واضحة للـ errors والـ auth.
- Upgrade لـ major version من غير قراءة الـ breaking changes (أسماء الـ Send APIs، الـ validation).
- نسيان
Policies/RolesفيConfigure(): اعمل fallback authorization policy تمنع الـ endpoints المفتوحة بالغلط.
Knowledge Check
هل FastEndpoints بديل عن فهم ASP.NET Core fundamentals؟
أين توضع قواعد مثل السعر أكبر من صفر؟
ما أهم trade-off عند إضافة framework third-party؟
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
خريطة التغطية: 9 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.