在ASP.NET中,您可以使用HttpContext.Current.Request對象來獲取當前請求的詳細信息,包括域名。以下是一個示例代碼片段:
using System;
using System.Web;
public class DomainNameHelper
{
public static string GetCurrentDomainName()
{
// 獲取當前請求的協議(HTTP或HTTPS)
string scheme = HttpContext.Current.Request.Url.Scheme;
// 獲取當前請求的主機名(包括端口號)
string host = HttpContext.Current.Request.Url.Host;
// 如果需要,可以在這里添加端口號
// int port = HttpContext.Current.Request.Url.Port;
// 組合協議和主機名以形成完整的域名
string domainName = scheme + "://" + host;
return domainName;
}
}
您可以在需要獲取當前域名的地方調用DomainNameHelper.GetCurrentDomainName()方法。例如,在一個ASPX頁面的代碼后臺中:
protected void Page_Load(object sender, EventArgs e)
{
string currentDomainName = DomainNameHelper.GetCurrentDomainName();
// 使用當前域名進行其他操作
}
請注意,如果您的應用程序部署在子目錄中,您可能需要根據實際情況調整代碼以包含子目錄路徑。