How to get the root URL

The code below is a terrible hack.

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

Instead of editing the line, how do I get the correct Url route in the first place?

For example, I want to get http://localhost:9999/ instead of http://localhost:9999/Users/Create

+8
asp.net-mvc
source share
4 answers

This is pretty ugly, but what 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) 
+10
source share

You can use the Content method of UrlHelper :

 string root = urlHelper.Content("~/"); 
+19
source share

The Sensation of ASP.NET Paths - Rick Strahl Weblog

How about this? Request.ApplicationPath

+3
source share
 var rootUrl = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); 
0
source share

All Articles