How to define simple nested routes in ASP.NET Core

Viewed 318

Is there a built-in way using ASP.NET Core to do standard nested routing in the same manner as in most other languages? How do I do in C# what I show below in Go and JS?

Example in Go using chi:

r := chi.NewRouter()
r.Use(amiddleware)                           // Use some middleware
r.Group(func(r chi.Router) {                 // A group with further configuration
  r.Use(another)                             // Middleware that only applies to group
  r.Route("/trunk", func(r chi.Router) {     // First level of a nested route
    r.Route("/branch", func(r chi.Router) {  // Next level
      r.Get("/leaf", Leaf)                   // An endpoint
    })
  })
})

func Leaf(w http.ResponseWriter, r *http.Request) { ... }

http.ListenAndServe(":8080", r)  // Start it up

Example in JS using express:

const app = express()
app.use(amiddleware)                          // Use middleware
app.use(Router().                             // A group with further configuration
  use(another).                               // Middleware that only applies to group
  use('/trunk', Router().                     // First level of a nested route
    use('/branch', Router().                  // Next level
      get('/leaf', leaf)                      // An endpoint
    )  
  )  
)

function leaf(req, res, next) { ... }

app.listen(8080)   // Start it up
1 Answers

In asp.net core, you can use route.MapRoute rules. But I personally feel that it is more cumbersome than the routing rules of the go language. There is no simple framework like gin and beego. You can refer to this document:

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs

There is a simpler way to set up routing like this:

 [ApiController]
    [Route("api/[controller]")]
    public class HomeController : Controller
    {


        [HttpGet("{id}")]
        public string Test(int id)
        {
            return "Test";
        }

        [HttpGet("test/{id:int}")]
        public string Test1(int id)
        {
            return "Test1";
        }
    }

Test url:https://localhost:port/api/home/1

Test1 url:https://localhost:port/api/home/test/1

More routing usage reference:

Routing to controller actions in ASP.NET Core

Related