我想动态获取 ASP.NET 应用程序的绝对根 Url。这需要是应用程序的完整根 URL,格式为:http(s)://hostname(:port)/
我一直在使用这个静态方法:
public static string GetSiteRootUrl()
{
string protocol;
if (HttpContext.Current.Request.IsSecureConnection)
protocol = "https";
else
protocol = "http";
StringBuilder uri = new StringBuilder(protocol + "://");
string hostname = HttpContext.Current.Request.Url.Host;
uri.Append(hostname);
int port = HttpContext.Current.Request.Url.Port;
if (port != 80 && port != 443)
{
uri.Append(":");
uri.Append(port.ToString());
}
return uri.ToString();
}
但是,如果范围内没有 HttpContext.Current
怎么办?
我在 CacheItemRemovedCallback
中遇到过这种情况。
最佳答案
对于 WebForms,此代码将返回应用程序根的绝对路径,无论应用程序的嵌套程度如何:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/")
上面的第一部分返回应用程序的方案和域名 (http://localhost
),不带尾部斜杠。 ResolveUrl
代码返回应用程序根目录 (/MyApplicationRoot/
) 的相对路径。通过将它们组合在一起,您可以获得 Web 表单应用程序的绝对路径。
使用 MVC:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/")
或者,如果您尝试直接在 Razor View 中使用它:
@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")
关于asp.net - 如何获取网站根 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5853294/