如何在C#中从DLL中找到基本URL?

3

在被C#.NET web应用程序调用的DLL内部,如何找到web应用程序的基本URL?


你能发一个完整的URL和你想要的例子吗? - Brian R. Bondy
5个回答

12

这个能行吗?

HttpContext.Current.Request.Url

更新:

要获取基本URL,您可以使用:

HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)

谢谢亚历山大 - 我使用HttpContext的那一部分解决了一些问题。 - Guy
你节省了我的时间!! - rebornx

1

如果这是一个可能被非 Web 项目引用的程序集,那么您可能希望避免使用 System.Web 命名空间。

我会使用 DannySmurf 的方法。


1
如Alexander所说,您可以使用HttpContext.Current.Request.Url,但如果您不想使用http://:
HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);

0

您可以使用 Assembly.GetExecutingAssembly() 获取 DLL 的程序集对象。

然后,调用 Server.MapPath,并将该程序集的 FullPath 传递给它以获取本地根路径。


我正在寻找网站的URL而不是目录路径。谢谢! - Guy

0

我想到了这个解决方案,但不确定它是否是最佳方案:

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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接