18

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?

4 Answers 4

18

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;
}
Sign up to request clarification or add additional context in comments.

Comments

14

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;

2 Comments

Exactly same in my situation. This should be marked as answer. Thank you
Works like a champ in .NET 8
2

Small correction to Kirk Larkin answer. Sometimes you have to use Template property instead of Name:

var ari = ControllerContext.ActionDescriptor.AttributeRouteInfo;
var route = ari.Name ?? ari.Template;

Comments

2

For .NET 6:

Accepted answer not working for me neither.

This worked however:

var routeName = (HttpContext.GetEndpoint() as RouteEndpoint).RoutePattern.RawText;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.