首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 取得網站根目錄 URL(含虛擬目錄)通用方法

     編輯:ASP.NET 基礎

需求

在後端程式碼中動態取得網站完整根目錄 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:51898Scheme + Host + Port,不含路徑
Request.ApplicationPath/ 或 /MyAppIIS 虛擬目錄路徑,根站點為 "/"
Request.Url.AbsoluteUrihttps://localhost:51898/MyApp/Page.aspx?q=1完整目前請求 URL

注意事項

  • 反向 Proxy / Load Balancer 環境:若網站位於 Nginx/ALB 之後,Request.Url 可能看到內部 IP/Port。需讀取 X-Forwarded-Proto、X-Forwarded-Host 標頭重建正確對外 URL。
  • 非 Web 執行緒:HttpContext.Current 為 null(如背景工作、Timer、SignalR Hub 建構子),不可使用此方法。需在有 Request 的地方預先解析並傳遞。
  • .NET Core / ASP.NET Core:請使用 IHttpContextAccessor.HttpContext.Request 搭配 GetDisplayUrl() 或自行組合 Scheme + Host + PathBase。

反向 Proxy 環境增強版

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 環境下讀取轉發標頭。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved