.NET API - إعداد الـRouting في Web API
1.4 .NET API - إعداد الـRouting في Web API
Routing (التوجيه) هو الآلية التي من خلالها يعرف Web API إلى أي Controller
وAction
يجب توجيه الطلب المرسل من العميل.
في ASP.NET Core Web API، يمكن إعداد التوجيه باستخدام Attribute Routing، وهو الأسلوب الأكثر استخدامًا مع الـ Web APIs.
🔧 ما هو Attribute Routing؟
Attribute Routing يعني كتابة التوجيه مباشرة فوق الـController أو الـAction باستخدام خصائص مثل: [Route]
و[HttpGet]
و[HttpPost]
.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok(new[] { "Laptop", "Mouse" });
[HttpGet("{id}")]
public IActionResult GetById(int id) => Ok($"Product #{id}");
[HttpPost]
public IActionResult Add(string name) => Ok($"Added {name}");
}
التوجيه في المثال أعلاه يعمل كالتالي:
GET /api/products
⟶GetAll()
GET /api/products/5
⟶GetById(5)
POST /api/products
⟶Add()
⚙️ ما الفرق بين [Route] و [HttpGet]؟
- [Route]: تحدد مسار التوجيه بشكل عام.
- [HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]: تحدد نوع الطلب (Method) المسموح به.
يمكنك أيضًا تخصيص المسار لكل Action:
[HttpGet("search/{name}")]
public IActionResult SearchByName(string name)
{
return Ok($"Searching for {name}");
}
⟶ GET /api/products/search/laptop
🛡️ تفعيل التوجيه في Program.cs
لكي يعمل الـRouting، يجب تفعيل الـControllers في Program.cs:
builder.Services.AddControllers();
app.MapControllers();
📌 خلاصة
- ✅ التوجيه هو ما يربط بين الرابط (URL) والدالة المناسبة في الـController.
- ✅ نستخدم Attribute Routing لكتابة المسارات بطريقة واضحة ومباشرة.
- ✅ يجب التأكد من تفعيل
MapControllers()
في التطبيق.
تعليقات
إرسال تعليق