Search code examples
c#asp.net-mvcmodel-view-controllerattributesasp.net-mvc-routing

How to get route value of action attribute in controller?


I have the action method defined like below:

[Route("example-page")]
public ActionResult MyAction()
{
    // I want to use "example-page" in here, like a query parameter.

    return View();
}

How to get action route value in controller?

I tried it like this:

var routeName = Url.RequestContext.RouteData.Values["action"].ToString();

It returns MyAction. I couldn't find another way.


Solution

  • From the Microsoft Dev Blogs:

    Routing is how ASP.NET MVC matches a URI to an action. MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application.

    Therefore, use the HttpRequest.Path to get the virtual path of the current request and it will match the URI mapped to the corresponded controller/action that this route attribute is applied.