ASP.NET 中 `Server.MapPath`、`Request` 路徑屬性 (`ApplicationPath`、`PathInfo`、`Url`、`ServerVariables`) 經常混淆。本文提供完整對照表、實際輸出範例、常見使用情境與最佳實務,幫助開發者精準取得所需路徑。
| 方法/屬性 | 回傳型別 | 說明 | 範例輸出 (假設網站根目錄 D:\WebApp\, 虛擬目錄 /MyApp, 頁面 /MyApp/Page.aspx) |
|---|---|---|---|
| Server.MapPath("~") | string (實體路徑) | 網站/應用程式**根目錄實體路徑** (含結尾 \) | D:\WebApp\ |
| Server.MapPath(".") | string | **當前頁面所在目錄**實體路徑 | D:\WebApp\PageDir\ |
| Server.MapPath("..") | string | **當前頁面父目錄**實體路徑 | D:\WebApp\ |
| Server.MapPath("~/Folder") | string | 網站根目錄下 Folder 實體路徑 | D:\WebApp\Folder\ |
| Server.MapPath("Folder") | string | 當前頁面目錄下 Folder 實體路徑 (相對路徑) | D:\WebApp\PageDir\Folder\ |
| Request.ApplicationPath | string (虛擬路徑) | 應用程式虛擬路徑 (以 / 開頭,不含結尾 /) | /MyApp |
| Request.PhysicalApplicationPath | string (實體路徑) | 應用程式實體根目錄 (同 Server.MapPath("~")) | D:\WebApp\ |
| Request.Path | string (虛擬路徑) | 請求路徑 (含虛擬目錄、頁面) | /MyApp/Page.aspx |
| Request.PathInfo | string | 路徑中超出實體檔案部分 (Wildcard Mapping 時用) | /extra/path |
| Request.Url | Uri | 完整請求 URL 物件 | https://localhost:1234/MyApp/Page.aspx |
| Request.Url.AbsoluteUri | string | 完整 URL 字串 | https://localhost:1234/MyApp/Page.aspx |
| Request.Url.GetLeftPart(UriPartial.Authority) | string | Scheme + Host + Port (網站根 URL) | https://localhost:1234 |
| Request.ServerVariables["APPL_PHYSICAL_PATH"] | string | 應用程式實體根目錄 (同 PhysicalApplicationPath) | D:\WebApp\ |
| Request.ServerVariables["PATH_TRANSLATED"] | string | 請求路徑對應的實體路徑 (含檔名) | D:\WebApp\PageDir\Page.aspx |
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
Response.Write("=== 實體路徑 ===\n");
Response.Write($"Server.MapPath(\"~\"): {Server.MapPath("~")}\n");
Response.Write($"Server.MapPath(\".\"): {Server.MapPath(".")}\n");
Response.Write($"Server.MapPath(\"..\"): {Server.MapPath("..")}\n");
Response.Write($"Server.MapPath(\"~/Upload\"): {Server.MapPath("~/Upload")}\n");
Response.Write($"Request.PhysicalApplicationPath: {Request.PhysicalApplicationPath}\n");
Response.Write($"Request.ServerVariables[\"APPL_PHYSICAL_PATH\"]: {Request.ServerVariables["APPL_PHYSICAL_PATH"]}\n");
Response.Write($"Request.ServerVariables[\"PATH_TRANSLATED\"]: {Request.ServerVariables["PATH_TRANSLATED"]}\n");
Response.Write("\n=== 虛擬/URL 路徑 ===\n");
Response.Write($"Request.ApplicationPath: {Request.ApplicationPath}\n");
Response.Write($"Request.Path: {Request.Path}\n");
Response.Write($"Request.PathInfo: {Request.PathInfo}\n");
Response.Write($"Request.Url: {Request.Url}\n");
Response.Write($"Request.Url.AbsoluteUri: {Request.Url.AbsoluteUri}\n");
Response.Write($"Request.Url.Authority: {Request.Url.Authority}\n");
Response.Write($"Request.Url.GetLeftPart(Authority): {Request.Url.GetLeftPart(UriPartial.Authority)}\n");
}
</script>
string savePath = Server.MapPath("~/Uploads/") + fileName; ✅ 標準做法string dbPath = Server.MapPath("~/App_Data/data.mdf"); ✅string imgUrl = Request.ApplicationPath + "/Images/logo.png"; 或 `Page.ResolveUrl("~/Images/logo.png")` ✅
// 路徑合併:使用 Path.Combine (自動處理 \)
string fullPath = Path.Combine(Server.MapPath("~/Uploads"), "sub", fileName);
// 確保目錄存在
string dir = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
// 取得相對網站根目錄的虛擬路徑 (供資料庫儲存)
string virtualPath = "~/Uploads/" + fileName; // 或用 VirtualPathUtility.ToAbsolute
// 物理路徑轉虛擬路徑 (罕見需求)
string virtualPath = fullPath.Replace(Server.MapPath("~"), "~").Replace("\\", "/");
public class MyService
{
private readonly IWebHostEnvironment _env;
public MyService(IWebHostEnvironment env) => _env = env;
public string GetUploadPath(string fileName)
{
// wwwroot 對應網站根目錄
string webRoot = _env.WebRootPath; // 實體路徑: D:\WebApp\wwwroot
string contentRoot = _env.ContentRootPath; // 專案根目錄: D:\WebApp
return Path.Combine(webRoot, "uploads", fileName);
}
// 取得虛擬路徑供前端使用
public string GetVirtualPath(string fileName) => $"/uploads/{fileName}";
}
原文結果顯示 `path1 = "F:ASP.NET_Projects...cfzsWebviewAtlasuploadcfzsWebviewAtlasupload"` 顯然是字串拼接錯誤 (重複路徑)。正確使用 `Path.Combine` 或確保 `Server.MapPath("upload")` 參數正確 (若頁面在 `/view/Atlas/`,則 `MapPath("upload")` 解析為 `/view/Atlas/upload`)。
總結:掌握 `Server.MapPath("~")` (實體根目錄)、`Request.ApplicationPath` (虛擬目錄)、`Request.Url` (完整 URL) 三大核心,配合 `Path.Combine` 處理路徑合併,即可應對 95% 路徑需求。避免字串拼接路徑,善用 `HostingEnvironment.MapPath` 脫離 HttpContext,部署至 IIS/容器/雲端皆能正常運作。