Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current route name with ASP.NET Core?

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?

like image 232
Junior Avatar asked Jul 13 '19 19:07

Junior


People also ask

How does routing work in ASP NET Core?

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.

What version of ASP NET Core has endpoint routing?

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:

How do I retrieve the current endpoint name from the MVC route?

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.

How does ASP NET Core work?

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.


2 Answers

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;
}
like image 150
Kirk Larkin Avatar answered Oct 20 '22 23:10

Kirk Larkin


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;
like image 40
Dave de Jong Avatar answered Oct 21 '22 01:10

Dave de Jong