如何从C#中的DLL中找到基本url
本文关键字:url DLL 中的 | 更新日期: 2023-09-27 17:47:24
从C#.NET web应用程序调用的DLL中,如何找到web应用程序的基本url?
这行得通吗?
HttpContext.Current.Request.Url
更新:
要获得基本URL,您可以使用:
HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)
如果它是一个可能被非web项目引用的程序集,那么您可能希望避免使用System.web命名空间。
我会用丹妮蓝精灵的方法。
正如Alexander所说,您可以使用HttpContext.Current.Request.Url,但如果您不想使用http://:
HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);
您可以使用Assembly.GetExecutingAssembly()来获取DLL的程序集对象。
然后,调用Server.MapPath,传入该Assembly的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;
}
}