在後端程式碼中動態取得網站完整根目錄 URL(如 https://localhost:51898 或 https://example.com/MyApp),用於產生絕對連結、郵件範本、API 回調網址等。
public static class UrlHelper
{
///
/// 取得應用程式根目錄完整 URL(含 Scheme、Host、Port、虛擬目錄),結尾不帶斜線。
/// 例:https://localhost:51898 或 https://example.com/MyApp
///
public static string GetRootUrl()
{
HttpContext ctx = HttpContext.Current;
if (ctx == null || ctx.Request == null)
throw new InvalidOperationException("無 HttpContext,僅限 Web 請求上下文呼叫。");
var req = ctx.Request;
var authority = req.Url.GetLeftPart(UriPartial.Authority); // https://host:port
var appPath = req.ApplicationPath; // / 或 /VirtualDir
// ApplicationPath 為 "/" 時不加,否則直接拼接(已含前導斜線)
return (appPath == null || appPath == "/") ? authority : authority + appPath;
}
///
/// 組合相對路徑為完整 URL。
///
public static string Combine(string relativePath)
{
if (string.IsNullOrWhiteSpace(relativePath)) return GetRootUrl();
string root = GetRootUrl();
if (!relativePath.StartsWith("/")) relativePath = "/" + relativePath;
return root + relativePath;
}
}
// 寄送郵件時產生驗證連結
string verifyLink = UrlHelper.Combine("/Account/VerifyEmail?token=" + token);
// 結果:https://example.com/MyApp/Account/VerifyEmail?token=xxx
// API 回調網址
string callbackUrl = UrlHelper.Combine("/api/payment/notify");
| 屬性 | 範例值 | 說明 |
|---|---|---|
Request.Url.GetLeftPart(UriPartial.Authority) | https://localhost:51898 | Scheme + Host + Port,不含路徑 |
Request.ApplicationPath | / 或 /MyApp | IIS 虛擬目錄路徑,根站點為 "/" |
Request.Url.AbsoluteUri | https://localhost:51898/MyApp/Page.aspx?q=1 | 完整目前請求 URL |
Request.Url 可能看到內部 IP/Port。需讀取 X-Forwarded-Proto、X-Forwarded-Host 標頭重建正確對外 URL。HttpContext.Current 為 null(如背景工作、Timer、SignalR Hub 建構子),不可使用此方法。需在有 Request 的地方預先解析並傳遞。IHttpContextAccessor.HttpContext.Request 搭配 GetDisplayUrl() 或自行組合 Scheme + Host + PathBase。public static string GetPublicRootUrl()
{
var req = HttpContext.Current.Request;
string scheme = req.Headers["X-Forwarded-Proto"] ?? req.Url.Scheme;
string host = req.Headers["X-Forwarded-Host"] ?? req.Url.Authority;
string pathBase = req.ApplicationPath;
if (pathBase == "/") pathBase = "";
return $"{scheme}://{host}{pathBase}";
}
GetLeftPart(UriPartial.Authority) + ApplicationPath 是最簡單可靠的取得根目錄 URL 方式。記得處理虛擬目錄為根目錄 ("/") 的邊界情況,並在 Proxy 環境下讀取轉發標頭。