如何获取根URL

ara*_*333 8 asp.net-mvc

下面的代码是一个可怕的黑客.

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

而不是编辑字符串,我如何获得正确的路由Url?

例如,我想要http://localhost:9999/而不是http://localhost:9999/Users/Create

Dar*_*rov 19

您可以使用以下内容方法UrlHelper:

string root = urlHelper.Content("~/");
Run Code Online (Sandbox Code Playgroud)

  • 是的,您需要引用UrlHelper.如果您在控制器中编写此代码,则您已经拥有了`Url`属性,您可以在其中调用`Content`方法.如果它在视图中:`<%= Url.Content("〜/")%>`. (2认同)

ngo*_*eff 11

这很难看,但是怎么样:

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

编辑:甚至更好:

uri.GetLeftPart(UriPartial.Authority)
Run Code Online (Sandbox Code Playgroud)