From 486e94f93b8854411e52939b14bfcf84844e65de Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Wed, 16 Jun 2021 16:19:37 +1000 Subject: [PATCH] Finished 'Attribute Route Constraints in ASP.NET MVC' --- 2_Routing.md | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/2_Routing.md b/2_Routing.md index 64e6def..807f6ea 100644 --- a/2_Routing.md +++ b/2_Routing.md @@ -391,4 +391,48 @@ namespace AttributeRoutingDemoInMVC.Controllers } } ``` -This will overwrite `"students"` route prefix. \ No newline at end of file +This will overwrite `"students"` route prefix. + +## Attribute Route Constraints in ASP.NET MVC + +### Attribute Route Constraints + +* **Attribute route constraints** = a set of rules that defined on routing parameters +* Defined by using `:` character. +* Can add additional requirement e.g. `min()`, `max()`, `range()` etc. + +e.g. We can create 2 action methods with same name with different route parameter + +```csharp +namespace AttributeRoutingDemoInMVC.Controllers +{ + [RoutePrefix("students")] + public class StudentsController : Controller + { + ... + + [HttpGet] + [Route("{studentID:int:range(1,3)}")] + // This will be translated to /students/2 + public ActionResult GetStudentDetails(int studentID) + { + Student studentDetails = students.FirstOrDefault(s => s.Id == studentID); + return View(studentDetails); + } + + [HttpGet] + [Route("{studentName:alpha}")] + // /student/Pranaya + public ActionResult GetStudentDetails(string studentName) + { + Student studentDetails = students.FirstOrDefault(s => s.Name == studentName); + return View(studentDetails); + } + ... + + } +} +``` + +* `[Route("{studentID:int:range(1,3)}")]` enforce route engine to use this action method **only if the given studentID is integer and it's within 1,2 or 3** +* `[Route("{studentName:alpha}")]` enforce route engine to use this action method **only if given studentID is alphabatic character strings** \ No newline at end of file