aspnet/Mvc

Get the list of all routes in ASP.NET Core

mdmoura opened this issue ยท 5 comments

I am trying to create a Route Debugger for ASP.NET Core 1. 1 where I need to display a list of all Routes.

So I created the following action inside a controller:

public IActionResult GetAllRoutes() {          
  var routes = this.RouteData.DataTokens;
  return Ok(routes);
}

This seems to only return parameters of the current route. I also tried:

public IActionResult GetAllRoutes() {    
  var routes = RouteData.Routers.OfType<RouteCollection>();
  return Ok(routes);
}

What is the best way to get a list of all routes including controller name, action name and url?

Is there a way to do this in ASP.NET Core 1.1?

What is the best way to get a list of all routes including controller name, action name and url?

Actions in MVC are either attribute routed or conventional routed.

You can find the convention routes in the route collection.

You can find all of the actions (along with their route data and attribute routes) by injecting the IActionDescriptorCollectionProvider service.

If you can ask more specific questions we can provide more useful information, but the above should be able to get you started.

@rynowak I just created the following controller:

  [Route("monitor")]
  public class MonitorController : Controller {
    private readonly IActionDescriptorCollectionProvider _provider;

    public MonitorController(IActionDescriptorCollectionProvider provider) {
      _provider = provider;
    }

    [HttpGet("routes")]
    public IActionResult GetRoutes() {
        var routes = _provider.ActionDescriptors.Items.Select(x => new { 
           Action = x.RouteValues["Action"], 
           Controller = x.RouteValues["Controller"], 
           Name = x.AttributeRouteInfo.Name, 
           Template = x.AttributeRouteInfo.Template 
        }).ToList();
        return Ok(routes);
    }
  }

How can I get the verb (GET, POST, ...) of each route?

Thank You

How can I get the verb (GET, POST, ...) of each route?

Look at the ActionDescriptor.ActionConstraints

Based on @mdmoura's comment, I did add something to have a simple display format including the role set on the route when it has [Authorize] or `[Authorize(Roles = "SomeUserRole")]'

Here's the output:

[
"GET -> api/monitor/routes", 
" -> api/monitor", 
"POST -> someRoute/test", 
"GET -> api/values", 
" -> Error", 
"-------- SECURED ROUTES --------", 
"[Authenticated] POST -> api/values", 
"[Authenticated] GET -> api/values",
"[Authenticated] GET -> api/users/current", 
"[Authenticated] GET -> api/users/{userId}", 
"[Administrator] PATCH -> api/users/{userId}", 
"[Authenticated] GET -> api/users/roles", 
"[Administrator] GET -> api/users"
]

Source:
https://gist.github.com/sam9291/dba558f417a04b1775b51b20eb0f96ab