Skip to content

Instantly share code, notes, and snippets.

@McKabue
Last active May 11, 2023 07:16
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save McKabue/b5caf25f9862b2488a9fa7898e22e86e to your computer and use it in GitHub Desktop.
Save McKabue/b5caf25f9862b2488a9fa7898e22e86e to your computer and use it in GitHub Desktop.
Get all routes, including default routes specified at start up
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Extentions
{
public static class GetAllRoutes
{
public static IApplicationBuilder AllRoutes(this IRouteBuilder routeBuilder, PathString pathString)
{
var app = routeBuilder.ApplicationBuilder;
app.Map(pathString, builder => {
builder.UseMiddleware<GetRoutes>(routeBuilder);
});
return app;
}
}
public class GetRoutes
{
private IRouteBuilder _routeBuilder;
public GetRoutes(RequestDelegate next, IRouteBuilder routeBuilder)
{
_routeBuilder = routeBuilder;
}
public async Task Invoke(HttpContext context)
{
try
{
var globals = _routeBuilder?.Routes?.Where(r => r.GetType() != typeof(AttributeRoute)).Select(r => {
Route _r = ((Route)(r));
return new
{
_r.Name,
Template = _r.RouteTemplate,
DefaultAction = _r.Defaults["action"],
DefaultController = _r.Defaults["controller"],
};
});
IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider = context.RequestServices.GetRequiredService<IActionDescriptorCollectionProvider>();
var actions = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Select(a => new RouteDescription
{
Action = a.RouteValues["action"],
Controller = a.RouteValues["controller"],
Name = a?.AttributeRouteInfo?.Name,
Templates = new string[] { a?.AttributeRouteInfo?.Template },
HttpMethods = a?.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods
});
await context.Response.WriteAsync(JsonConvert.SerializeObject(new { globals, actions }));
return;
}
catch (Exception e)
{
await context.Response.WriteAsync($"{e.Message}");
return;
}
}
}
}
@McKabue
Copy link
Author

McKabue commented May 7, 2018

Use it like this:

app.UseMvc(routes =>
            {
                routes.AllRoutes("/allroutes");

                routes.MapRoute(
                    name: "default",
                    template: "{*url}",
                    defaults: new { controller = "Home", action = "Index" });
            });

the important line is routes.AllRoutes("/allroutes");, when you go to the browser at /allroutes, you will get all routes...

{
   "globals":[
      {
         "Bame":"default",
         "Template":"{*url}",
         "DefaultAction":"Index",
         "DefaultController":"Home"
      }
   ],
   "actions":[
      {
         "Action":"Search",
         "Controller":"API",
         "Name":null,
         "Templates":[
            "api/search"
         ],
         "HttpMethods":[
            "GET"
         ]
      },
      {
         "Action":"TagsSearch",
         "Controller":"API",
         "Name":null,
         "Templates":[
            "api/tags/search"
         ],
         "HttpMethods":[
            "GET"
         ]
      },
      {
         "Action":"ClientRoutes",
         "Controller":"API",
         "Name":null,
         "Templates":[
            "api/routes/client"
         ],
         "HttpMethods":[
            "GET"
         ]
      },
      {
         "Action":"Index",
         "Controller":"Home",
         "Name":null,
         "Templates":[
            null
         ],
         "HttpMethods":null
      }
   ]
}

@davidikin45
Copy link

davidikin45 commented May 17, 2018

Good code!

I added another property to determine if the action is authorized.

Authorized = a?.GetCustomAttributes().Any()

public static IEnumerable GetCustomAttributes(this Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor) where T : Attribute
{
var controllerActionDescriptor = actionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
return controllerActionDescriptor.MethodInfo.ReflectedType.GetCustomAttributes(typeof(T), true).Select(a => (T)a);
}
return Enumerable.Empty();
}

@pradeeptillid
Copy link

Is there any way to get params?

@ManfredLange
Copy link

The gist seems to be missing the RouteDescription. It can be safely removed, however, for the code to work. In that case it just creates an instance of an anonymous type. Thank you for sharing! 😄

@mrivasa
Copy link

mrivasa commented Jul 30, 2020

Hope there were something like this for .net framework (not core). Pointers anybody? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment