ASP.net nesting routes with Route tags

Viewed 350

I'm brand new to C# and ASP.Net

I am trying to model some endpoints:

/api/sites/
/api/sites/{id}/
/api/sites/{id}/readers/
/api/sites/{id}/readers/{id}/

I already have a SitesController

[Route("api/[controller]")]
[ApiController]
public class SitesController : ControllerBase {
    [HttpGet("{id:length(24)}")]
    public ActionResult<Site> Get(string id) {}



}

I've tried adding a ReadersController inside the SitesController class

[Route("{id:length(24)}/[controller]}")]
[ApiController]
public class ReadersController {
    [HttpGet]
    public string Get() => "test";
}

I can't hit the endpoint /api/sites/{id}/readers/ though so I'm not sure I'm doing this right. Is there some way I can do this while still using the [Route] tags?

2 Answers

If you are building apis with asp.net core, please check this.

Link

You can use routes.MapRoute functions as many as you can. Like this.

routes.MapRoute(
    name: "default_route",
    template: "{controller}/{action}/{id?}");

routes.MapRoute(
    name: "default_route",
    template: "{controller}/{action}/{id}/readers/{id?}");

You shouldn't be nesting controller classes. Make a new class for ReadersController then setup the routes like this:

[Route("api/[controller]")]
[ApiController]
public class SitesController : ControllerBase {
    [HttpGet("{siteId:length(24)}")]
    public ActionResult<Site> Get(string siteId) {}
}

[Route("api/sites/{siteId:length(24)}/[controller]")]
[ApiController]
public class ReadersController {
    [HttpGet]
    public string Get() => "test";

    [HttpGet("{readerId:length(24)}")]
    public ActionResult<Site> Get(string siteId, string readerId) {}
}

You can use routes.MapRoute to create more complex rules however if you want to keep it easy and specify routes for each individual endpoint then you can carry on using HttpGet or Route attributes. Or if you want to make it explicit you can write out the whole route in each HttpGet and ignore the Route attribute on the controller.

Related