在 ASP.NET 中取得網站根目錄 URL (如 `https://www.example.com/` 或 `https://www.example.com/MyApp/`) 是生成絕對連結、回調網址、郵件連結的基礎需求。本文提供健壯的 `GetRootUri` 方法,處理虛擬目錄、負載平衡器/反向代理 (X-Forwarded-Host)、HTTPS 連接埠等真實環境複雜性。
public static string GetRootUri()
{
string appPath = "";
HttpContext current = HttpContext.Current;
if (current != null)
{
HttpRequest request = current.Request;
string urlAuthority = request.Url.GetLeftPart(UriPartial.Authority); // 含 scheme+host+port
if (request.ApplicationPath == null || request.ApplicationPath == "/")
appPath = urlAuthority; // 直接安裝於網站根目錄
else
appPath = urlAuthority + request.ApplicationPath; // 虛擬目錄
}
return appPath;
}
生產環境常部署於 Nginx/IIS ARR/雲端負載平衡器後方,`Request.Url` 可能反映內部私有 IP/Port/HTTP,而非公開網址。需檢查標準代理標頭。
public static class UrlHelper
{
///
/// 取得公開根目錄 URL (含虛擬目錄),正確處理反向代理
///
public static string GetPublicRootUri(HttpRequest request = null)
{
request = request ?? HttpContext.Current?.Request;
if (request == null) return "";
// 1. 判斷 Scheme (HTTP/HTTPS)
string scheme = "http";
if (request.IsSecureConnection) scheme = "https";
// 檢查代理轉發標頭 (常見: X-Forwarded-Proto, X-Forwarded-Ssl, Front-End-Https)
string forwardedProto = request.Headers["X-Forwarded-Proto"] ?? request.Headers["Front-End-Https"];
if (!string.IsNullOrEmpty(forwardedProto) && forwardedProto.Equals("https", StringComparison.OrdinalIgnoreCase))
scheme = "https";
else if (forwardedProto == "on") // Front-End-Https: on
scheme = "https";
// 2. 判斷 Host (包含 Port)
string host = request.Url.Host;
int port = request.Url.Port;
// 檢查 X-Forwarded-Host / X-Host / Host 標頭
string forwardedHost = request.Headers["X-Forwarded-Host"] ?? request.Headers["X-Host"];
if (!string.IsNullOrEmpty(forwardedHost))
{
// 可能包含多個 host (鏈式代理),取第一個
host = forwardedHost.Split(',')[0].Trim();
// 解析 port (如果有)
if (host.Contains(":"))
{
var parts = host.Split(':');
host = parts[0];
if (int.TryParse(parts[1], out int p)) port = p;
}
}
else if (request.Headers["Host"] != null)
{
// 標準 Host 標頭
string hostHeader = request.Headers["Host"];
if (hostHeader.Contains(":"))
{
var parts = hostHeader.Split(':');
host = parts[0];
if (int.TryParse(parts[1], out int p)) port = p;
}
else host = hostHeader;
}
// 3. 建構 Authority (host:port)
string authority = host;
bool isStandardPort = (scheme == "http" && port == 80) || (scheme == "https" && port == 443);
if (!isStandardPort) authority += ":" + port;
// 4. 應用程式路徑 (虛擬目錄)
string appPath = request.ApplicationPath;
if (appPath != null && appPath != "/")
appPath = appPath.TrimEnd('/') + "/"; // 確保結尾有 /
else
appPath = "/";
return $"{scheme}://{authority}{appPath}";
}
///
/// 組合絕對 URL
///
public static string Combine(string baseUrl, string relativePath)
{
if (string.IsNullOrEmpty(baseUrl)) return relativePath;
if (string.IsNullOrEmpty(relativePath)) return baseUrl.TrimEnd('/');
return baseUrl.TrimEnd('/') + "/" + relativePath.TrimStart('/');
}
}
// 取得根目錄
string root = UrlHelper.GetPublicRootUri();
// 結果範例: "https://www.example.com/MyApp/"
// 組合完整 URL
string apiUrl = UrlHelper.Combine(root, "api/users");
string resetLink = UrlHelper.Combine(root, $"account/reset?token={token}");
// 郵件範本中使用
string body = $"請點擊 這裡 驗證信箱。";
若不想依賴 Request 標頭推斷,可在 `web.config` 明確設定:
<appSettings>
<add key="AppBaseUrl" value="https://www.example.com/MyApp/" />
</appSettings>
public static string GetConfiguredRootUri()
{
return ConfigurationManager.AppSettings["AppBaseUrl"]?.TrimEnd('/') + "/";
}
優點:確定性、不受代理影響。缺點:部署多環境 (Dev/Staging/Prod) 需變更設定檔。
// 在 Controller/Service 中注入 IHttpContextAccessor
public string GetRootUri(HttpRequest request)
{
var scheme = request.Scheme; // 自動處理 ForwardedHeaders 中介軟體
var host = request.Host.Value; // 包含 port (若非標準)
var pathBase = request.PathBase.Value; // 虛擬目錄
return $"{scheme}://{host}{pathBase}/";
}
// Startup.cs 設定 ForwardedHeaders (關鍵!)
services.Configure(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
options.KnownNetworks.Clear(); // 信任所有代理 (或加入已知代理 IP 範圍)
options.KnownProxies.Clear();
});
app.UseForwardedHeaders(); // 必須在 UseAuthentication/UseMvc 之前
| 部署環境 | Request.Url | 預期 GetPublicRootUri | 關鍵標頭 |
|---|---|---|---|
| 本機 IIS Express | https://localhost:1234/MyApp/ | https://localhost:1234/MyApp/ | - |
| IIS 根網站 | https://server/ | https://server/ | - |
| IIS 虛擬目錄 | https://server/MyApp/ | https://server/MyApp/ | - |
| Nginx 反向代理 (HTTPS 卸載) | https://10.0.0.5:8080/MyApp/ | https://www.example.com/MyApp/ | X-Forwarded-Proto: https X-Forwarded-Host: www.example.com |
| Azure App Service / AWS ELB | https://172.16.0.4:80/ | https://myapp.azurewebsites.net/ | X-Forwarded-Proto: https Host: myapp.azurewebsites.net |
| Docker 容器內部 | https://container:80/App/ | https://api.example.com/App/ | X-Forwarded-Proto, X-Forwarded-Host |
總結:取得網站根目錄 URL 看似簡單,實際部署環境 (虛擬目錄、反向代理、HTTPS 卸載、負載平衡) 讓 `Request.Url` 不可靠。建議採用**進階版本**檢查 `X-Forwarded-*` 標頭,或在 `web.config` 明確設定 `AppBaseUrl`。ASP.NET Core 則務必設定 `ForwardedHeadersMiddleware`。將此邏輯封裝為 `UrlHelper.GetPublicRootUri()` 統一調用,避免專案各處重複且不一致的實作。