Skip to content

Instantly share code, notes, and snippets.

@pwelter34
Last active December 1, 2021 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwelter34/0d7705d12264c04bdf51004f7689dfab to your computer and use it in GitHub Desktop.
Save pwelter34/0d7705d12264c04bdf51004f7689dfab to your computer and use it in GitHub Desktop.
Middleware to debug configuration and routes
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace Demo.Middleware;
public class HostDebuggerOptions
{
public string RouteDebuggerPath { get; set; } = "/route-debugger";
public string ConfigurationDebuggerPath { get; set; } = "/config-debugger";
}
public static class HostDebuggerExtensions
{
public static IApplicationBuilder UseHostDebugger(this IApplicationBuilder app, HostDebuggerOptions? options = null)
{
return app.UseMiddleware<HostDebuggerMiddleware>(options ?? new HostDebuggerOptions());
}
}
public class HostDebuggerMiddleware
{
private readonly RequestDelegate _next;
private readonly HostDebuggerOptions _options;
private readonly IConfiguration _configuration;
public HostDebuggerMiddleware(RequestDelegate next, HostDebuggerOptions options, IConfiguration configuration)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_options = options ?? throw new ArgumentNullException(nameof(options));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public Task Invoke(HttpContext context, IActionDescriptorCollectionProvider? provider = null)
{
if (context is null)
throw new ArgumentNullException(nameof(context));
if (context.Request.Path == _options.RouteDebuggerPath && provider != null)
{
var routes = provider.ActionDescriptors.Items.Select(x => new
{
Action = x.RouteValues.ContainsKey("Action") ? x.RouteValues["Action"] : null,
Controller = x.RouteValues.ContainsKey("Controller") ? x.RouteValues["Controller"] : null,
Page = x.RouteValues.ContainsKey("Page") ? x.RouteValues["Page"] : null,
x.AttributeRouteInfo?.Name,
x.AttributeRouteInfo?.Template,
Contraint = x.ActionConstraints
}).ToArray();
var routesJson = JsonSerializer.Serialize(routes, new JsonSerializerOptions() { WriteIndented = true });
context.Response.ContentType = "application/json";
return context.Response.WriteAsync(routesJson, Encoding.UTF8);
}
else if (context.Request.Path == _options.ConfigurationDebuggerPath && _configuration is IConfigurationRoot configurationRoot)
{
var debugView = configurationRoot.GetDebugView();
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync(debugView, Encoding.UTF8);
}
return _next(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment