I have an application that is written on the top of ASP.NET Core 2.2 framework.
I have the following controller
public class TestController : Controller
{
[Route("some-parameter-3/{name}/{id:int}/{page:int?}", Name = "SomeRoute3Name")]
[Route("some-parameter-2/{name}/{id:int}/{page:int?}", Name = "SomeRoute2Name")]
[Route("some-parameter-1/{name}/{id:int}/{page:int?}", Name = "SomeRoute1Name")]
public ActionResult Act(ActVM viewModel)
{
// switch the logic based on the route name
return View(viewModel);
}
}
How can I get the route name in the action and/or the view?
By default ASP.NET Core uses a routing algorithm that trades memory for CPU time. This has the nice effect that route matching time is dependent only on the length of the path to match and not the number of routes.
The endpoint routing system described in this document is new as of ASP.NET Core 3.0. However, all versions of ASP.NET Core support the same set of route template features and route constraints. The following example shows routing with health checks and authorization:
In ASP.NET Core 2.2 we registered endpoint routing like so: To retrieve the current endpoint name (from the MVC route) we used the following extension: As of ASP.NET Core 3.0, the IRouteValuesAddressMetadata type has been removed.
ASP.NET Core: Processes the URL path against the set of endpoints and their route templates, collecting all of the matches. Takes the preceding list and removes matches that fail with route constraints applied.
Inside of a controller, you can read the AttributeRouteInfo
from the ControllerContext
's ActionDescriptor
. AttributeRouteInfo
has a Name
property, which holds the value you're looking for:
public ActionResult Act(ActVM viewModel)
{
switch (ControllerContext.ActionDescriptor.AttributeRouteInfo.Name)
{
// ...
}
return View(viewModel);
}
Inside of a Razor view, the ActionDescriptor
is available via the ViewContext
property:
@{
var routeName = ViewContext.ActionDescriptor.AttributeRouteInfo.Name;
}
For me the answer by @krik-larkin didn't work as AttributeRouteInfo
was always null in my case.
I used the following code instead:
var endpoint = HttpContext.GetEndpoint() as RouteEndpoint;
var routeNameMetadata = endpoint?.Metadata.OfType<RouteNameMetadata>().SingleOrDefault();
var routeName = routeNameMetadata?.RouteName;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With