在被C#.NET web应用程序调用的DLL内部,如何找到web应用程序的基本URL?
在被C#.NET web应用程序调用的DLL内部,如何找到web应用程序的基本URL?
这个能行吗?
HttpContext.Current.Request.Url
更新:
要获取基本URL,您可以使用:
HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)
如果这是一个可能被非 Web 项目引用的程序集,那么您可能希望避免使用 System.Web 命名空间。
我会使用 DannySmurf 的方法。
HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);
您可以使用 Assembly.GetExecutingAssembly() 获取 DLL 的程序集对象。
然后,调用 Server.MapPath,并将该程序集的 FullPath 传递给它以获取本地根路径。
我想到了这个解决方案,但不确定它是否是最佳方案:
string _baseUrl = String.Empty;
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
_baseURL = "http://" + HttpContext.Current.Request.Url.Host;
if (!HttpContext.Current.Request.Url.IsDefaultPort)
{
_baseURL += ":" + HttpContext.Current.Request.Url.Port;
}
}