Skip to content
This repository has been archived by the owner on Apr 29, 2020. It is now read-only.

Latest commit

 

History

History
59 lines (43 loc) · 1.44 KB

Hierarchical-Routes.md

File metadata and controls

59 lines (43 loc) · 1.44 KB

Hierarchical (a.k.a. RESTful) Routes

Hierarchical routes are routes where one or more parameters go before the action parameter, for example:

Book/{id}
Book/{id}/Chapter/{chapterId}/{page}

There are 2 ways to achieve this. One, is by decorating controller properties with the FromRoute attribute, for example:

public class BookController : Controller {
    
    [FromRoute]
    public int id { get; set; }
    
    protected override void Initialize(RequestContext requestContext) {
    
        base.Initialize(requestContext);
        this.BindRouteProperties();
    }
    
    public ActionResult Index() {
        ...
    }
    
    public ActionResult Chapter([FromRoute]int chapterId, [FromRoute]int page = 1) {
        ...
    }
}

Properties decorated with the FromRoute attribute are always required.

The other way is by using the CustomRoute attribute:

public class BookController : Controller {
    
    [CustomRoute("{id}")]
    public ActionResult Details([FromRoute]int id) {
        ...
    }
    
    [CustomRoute("{id}/{action}/{chapterId}/{page}")]
    public ActionResult Chapter([FromRoute]int id, [FromRoute]int chapterId, [FromRoute]int page = 1) {
        ...
    }
}

The advantage of using the CustomRoute attribute is that you can implement Book and Book/{id} on the same controller.

See Also