Last active
May 11, 2023 07:16
-
-
Save mckabue/b5caf25f9862b2488a9fa7898e22e86e to your computer and use it in GitHub Desktop.
Get all routes, including default routes specified at start up
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hope there were something like this for .net framework (not core). Pointers anybody? Thanks.