Search code examples
asp.netasp.net-mvcasp.net-mvc-routing

How to know which route is currently mapped


I have a route as

routes.MapRoute(
                "User", // Route name
                "Person/{action}", // URL with parameters
                new { controller = "User" } // Parameter defaults
            );

that means if I put url like

http://localhost/myApp/Person/Detail

then it should invoke Detail action of User controller, right?

Ok, I have done it and routing also works good, means it invoke action properly.

Now if I want to get controller name then I will use

ControllerContext.RouteData.Values["controller"];

and that will give me User, but I want it to be Person (i.e. as in URL). How can I get that?


Solution

  • The Request.Url property of Controller will return a Uri object containing details of the current url, including the segments.

    string[] segments = Request.Url.Segments;
    // returns ["/", "Person/", "Detail"]
    
    string value = segments[1].Remove(segments[1].Length - 1);;
    // returns "Person"