tags:

views:

28

answers:

3

The code below is a dreadful hack.

Uri linkUri = HttpContext.Current.Request.Url; string link = linkUri.ToString().Substring(0, linkUri.ToString().IndexOf("Users/Create"));

Instead of editing the string, how do I get the correct route Url in the first place? For example I want to get http://localhost:9999/ instead of http://localhost:9999/Users/Create

A: 

You could use the Content method of UrlHelper:

string root = urlHelper.Content("~/");
Darin Dimitrov
I get an error message; "An object reference is required for the non-static field method, or property 'System.Web.Mvc.UrlHelper.Content(string)'"
arame3333
Yes, you need a reference to an UrlHelper. If you are writing this code in a controller you already have the `Url` property on which you could invoke the `Content` method. If it is in a view: `<%= Url.Content("~/") %>`.
Darin Dimitrov
I am not using this code in a View. I am coding within a class, where UrlHelper does not have a Content method.
arame3333
+1  A: 

It's pretty ugly, but how about:

Uri uri = new Uri("http://localhost:9999/Users/Create");
string link = string.Format("{0}://{1}:{2}", uri.Scheme, uri.Host, uri.Port);

Edit: or even better:

uri.GetLeftPart(UriPartial.Authority)
ngoozeff
Yes this is certainly an improvement. I will wait and see what other answers I get, but this is the best so far.
arame3333
+1  A: 

Making Sense of ASP.NET Paths - Rick Strahl's Web Log

How about this? Request.ApplicationPath

takepara
I can only access the Request object as follows; HttpContext.Current.Request.ApplicationPath. All this returns is a "/".
arame3333