簡體   English   中英

如何從C#中的DLL中找到基本URL?

[英]How do you find the base url from a DLL in C#?

從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但是如果你不想使用http://:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM