Breaking String URL into Route Data ASP.NET MVC

Getting your route data into URL format is easy – simply use the UrlHelper (Url.Action).

But reversing this, and parsing a URL is a bit more fiddly:

string path = "";
string queryString = "";
System.Web.Routing.RouteData routeFromUrl = System.Web.Routing.RouteTable.Routes.GetRouteData(new HttpContextWrapper(new HttpContext(new HttpRequest(null, new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port, path).ToString(), queryString), new HttpResponse(new System.IO.StringWriter()))));

You can then use the RouteData.Values to extract the information you need:

string controller = routeFromUrl.Values["controller"];
string action = routeFromUrl.Values["action"];
string id = routeFromUrl.Values["id"];

If you just want to get this information for the current page, no need to do the first step, the current RouteData is in a property called RouteData on the controller. If you’re not in the controller, you can use the GetRouteData method with the current HttpContext and HttpResponse.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s