Skip to content

Instantly share code, notes, and snippets.

@McKabue
Last active May 11, 2023 07:16
Show Gist options
  • 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;
}
}
}
}
@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