How to parse a string URL into MVC Route Values (area, controller, action, querystring)?
Asked Answered
C

2

8

Is there a method to extract the area, controller, action, and querystring from a URL in ASP.NET MVC? Don't want to reinvent the wheel implementing my own if there's already a way to do it.

Thanks!

Cogitable answered 2/9, 2010 at 13:28 Comment(0)
C
6

I was able to get it from here:

String URL to RouteValueDictionary

To get the area from this example I used:

string area = routeData.DataTokens["area"].ToString();

Cogitable answered 2/9, 2010 at 15:28 Comment(0)
K
-2

You could pull this information from the routes:

var controller = RouteData.Values["controller"];
var action = RouteData.Values["action"];
var action = RouteData.Values["area"];

As far as the query string is concerned you could pull it from the Request:

var queryString = Request.Url.Query;

UPDATE:

If the url is coming from a DB:

var uri = new Uri(someStringThatRepresentsTheUrlAndComesFromADb);
var queryString = uri.Query;
Kkt answered 2/9, 2010 at 13:35 Comment(2)
Hmm that's actually cool, but the URL string is not from the current context, it's coming from a DB.Cogitable
Thanks, yeah I can get the querystring. The issue is in getting the area, controller, action really. Sometimes an action has a trailing '/' and sometimes it doesn't, so counting from the right can be misleading. On the other hand, an application can be within different directory structures in IIS, so counting positions from the left isn't straightforward either...Cogitable

© 2022 - 2024 — McMap. All rights reserved.