Finished 'Attribute Route Constraints in ASP.NET MVC'
parent
716a09427b
commit
486e94f93b
44
2_Routing.md
44
2_Routing.md
@ -392,3 +392,47 @@ namespace AttributeRoutingDemoInMVC.Controllers
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
This will overwrite `"students"` route prefix.
|
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**
|
Loading…
x
Reference in New Issue
Block a user