Last active
April 23, 2023 15:27
-
-
Save JacopoWolf/5a3219f8310cf2883d1043022df0e400 to your computer and use it in GitHub Desktop.
ASP .NET controller to monitor currently registered routes
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.Mvc; | |
using Microsoft.AspNetCore.Mvc.ActionConstraints; | |
using Microsoft.AspNetCore.Mvc.Infrastructure; | |
// namespace here | |
[ApiController] | |
[Route("api/[controller]")] // update route with your preference here | |
public class MonitorController : ControllerBase | |
{ | |
[HttpGet] | |
[HttpOptions] | |
[Produces(MIME.TXT)] | |
public string Index() => "ok"; | |
#if DEBUG | |
[HttpGet(nameof(Routes))] | |
public IEnumerable<object> Routes([FromServices] IActionDescriptorCollectionProvider actionsDesc) | |
{ | |
return actionsDesc.ActionDescriptors.Items | |
.Where(ad => ad.AttributeRouteInfo is not null) | |
.Select(ad => | |
new | |
{ | |
methods = string.Join('|', ad.ActionConstraints? | |
.Where(c => c is HttpMethodActionConstraint) | |
.SelectMany(c => (c as HttpMethodActionConstraint)!.HttpMethods) | |
?? Enumerable.Empty<string>()), | |
ad.AttributeRouteInfo!.Template, | |
ad.AttributeRouteInfo!.Name, | |
ad.DisplayName | |
} | |
); | |
} | |
[HttpGet(nameof(Throw))] | |
public IActionResult Throw() | |
{ | |
throw new Exception("this is a test exception"); | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment