我想动态获取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();
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我没有HttpContext.Current
范围怎么办?我遇到过这样的情况CacheItemRemovedCallback
.
sal*_*uce 77
对于WebForms,此代码将返回应用程序根目录的绝对路径,而不管应用程序的嵌套方式如何:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/")
Run Code Online (Sandbox Code Playgroud)
上面的第一部分返回application(http://localhost
)的方案和域名,没有尾部斜杠.的ResolveUrl
代码返回到应用程序根的相对路径(/MyApplicationRoot/
).通过将它们组合在一起,您可以获得Web表单应用程序的绝对路径.
使用MVC:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/")
Run Code Online (Sandbox Code Playgroud)
或者,如果您尝试在Razor视图中直接使用它:
@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")
Run Code Online (Sandbox Code Playgroud)
Den*_*cob 11
public static string GetAppUrl()
{
// This code is tested to work on all environments
var oRequest = System.Web.HttpContext.Current.Request;
return oRequest.Url.GetLeftPart(System.UriPartial.Authority)
+ System.Web.VirtualPathUtility.ToAbsolute("~/");
}
Run Code Online (Sandbox Code Playgroud)
小智 6
public static string GetFullRootUrl()
{
HttpRequest request = HttpContext.Current.Request;
return request.Url.AbsoluteUri.Replace(request.Url.AbsolutePath, String.Empty);
}
Run Code Online (Sandbox Code Playgroud)
我通过在 AppSettings(“SiteRootUrl”)中添加 web.config 设置解决了这个问题。简单而有效,但需要维护另一个配置设置。
归档时间: |
|
查看次数: |
86680 次 |
最近记录: |