In AspNetCore, given a FilterContext, I'm looking to get a route template e.g.
{controller}/{action}/{id?}
In Microsoft.AspNet.WebApi I could get the route template from:
HttpControllerContext.RouteData.Route.RouteTemplate
In System.Web.Mvc I could get this from:
ControllerContext.RouteData.Route as RouteBase
In AspNetCore there is:
FilterContext.ActionDescriptor.AttributeRouteInfo.Template
However, not all routes are attribute routes.
Based on inspection if the attribute is not available, default routes and/or mapped routes can be assembled from:
FilterContext.RouteData.Routers.OfType<Microsoft.AspNetCore.Routing.RouteBase>().First()
but I'm looking for a documented or a simply better approach.
Update (24 Jan 2021)
There is a much much simpler way of retrieving the
RoutePattern
directly via theHttpContext
.GetEndpoint()
is an extension method provided inEndpointHttpContextExtensions
class insideMicrosoft.AspNetCore.Http
namespaceOld Answer (Too much work)
All the route builders for an ASP.NET Core app (at least for 3.1) are exposed and registered via
IEndpointRouteBuilder
, but unfortunately, this is not registered with the DI container, so you can't acquire it directly.The only places where I have seen this interface being exposed, are in the middlewares. So you can build a collection or dictionary out of one of those middlewares, and then use that for your purposes.e.g
Program.cs
Extension class to build your endpoint collection / dictionary
Startup.cs
And then you can use that Dictionary or Collection, to retrieve the Route Template from the FilterContext.
To tackle the case of overloaded actions, a list of strings is used for route template (instead of just a string in the Dictionary)
You can use the
ActionDescriptor.Parameters
in conjunction withRoutePattern.Parameters
to generate a unique display name for that route.