【问题标题】:How do you find the base url from a DLL in C#?如何从 C# 中的 DLL 中找到基本 url?
【发布时间】:2010-09-16 19:41:24
【问题描述】:

在 C#.NET Web 应用程序调用的 DLL 中,如何找到 Web 应用程序的基本 url?

【问题讨论】:

  • 您能否发布一个完整 URL 的示例以及您想要的内容?

标签: c# .net asp.net url web-applications


【解决方案1】:

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

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

【讨论】:

  • 我正在寻找网站的 URL,而不是目录路径。谢谢!
【解决方案2】:

这行得通吗?

HttpContext.Current.Request.Url

更新:

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

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

【讨论】:

  • 感谢 Alexander - 我使用 HttpContext 的那部分解决了一些问题。
  • 你节省了我的时间!!
【解决方案3】:

我想出了这个,虽然我不确定它是否是最好的解决方案:

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

【讨论】:

    【解决方案4】:

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

    我会使用 DannySmurf 的方法。

    【讨论】:

      【解决方案5】:

      正如 Alexander 所说,您可以使用 HttpContext.Current.Request.Url 但如果您不想使用 http://:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-12
        • 1970-01-01
        • 1970-01-01
        • 2010-09-15
        • 2014-10-16
        • 2013-07-28
        • 2011-10-31
        • 1970-01-01
        相关资源
        最近更新 更多