开发者

How to get the root Url

开发者 https://www.devze.com 2023-01-16 03:07 出处:网络
The code below is a dreadful hack. Uri linkUri = HttpContext.Current.Request.Url; string link = linkUri.ToString().开发者_Python百科Substring(0, linkUri.ToString().IndexOf(\"Users/Create\"));

The code below is a dreadful hack.

Uri linkUri = HttpContext.Current.Request.Url;
string link = linkUri.ToString().开发者_Python百科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


You could use the Content method of UrlHelper:

string root = urlHelper.Content("~/");


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)


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

How about this? Request.ApplicationPath


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

精彩评论

暂无评论...
验证码 换一张
取 消