蓝色天空网mbsky.com · 知识 · 实践 · 创造Web Forms · 本地阅读预览
教程 / .NET / Web Forms

WebPages 文件夹

详解 ASP.NET Web Pages 逻辑与物理文件夹结构、虚拟名称与物理路径映射,以及 ~ 运算符、Server.MapPath 与 Href 三种路径解析工具及其 ASP.NET Core 现代替代。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

逻辑文件夹结构与物理文件夹结构

合理组织目录并正确区分虚拟路径与物理路径,是保证 ASP.NET 站点可移植性与文件安全性的基础。本章重点介绍逻辑与物理文件夹结构、虚拟名称与物理名称,以及 Web URL 和路径工具。

一个典型的 ASP.NET Web Pages 站点按职责划分逻辑文件夹:`Account` 存放登录与账号安全页面;`App_Data` 存放数据库与数据文件(受运行时保护,禁止浏览器直接下载);`Images` 存放图片资源;`Scripts` 存放浏览器端脚本;`Shared` 存放布局页、公共样式等共享模板。原页此处配有一张站点逻辑文件夹结构示意图(未入本地缓存,已在待办项登记)。

与站点内的逻辑树相对应,物理文件夹结构反映站点在服务器磁盘上的真实位置,例如 `Images` 目录在磁盘上可能位于 `C:\Documents\MyWebSites\Demo\Images`。相应地,同一张图片的虚拟名称可能是 `Images/pic31.jpg`,而其磁盘物理名称则为 `C:\Documents\MyWebSites\Demo\Images\pic31.jpg`。

URL、虚拟路径与物理路径的关系

浏览器通过 URL(例如 `https://example.com/html/html-tutorial.html`)访问网页,Web 服务器将其映射到本地磁盘上的物理文件(例如 `C:\MyWebSites\example\html\html-tutorial.html`)。磁盘驱动器的根目录写作 `C:`,而网站的虚拟根目录始终写作 `/`(斜线)。虚拟路径相当于物理路径的可移植简写,当更换域名或将站点迁移至其他服务器目录时无需批量重写代码。ASP.NET 围绕路径转换提供了三件核心工具:`~` 运算符、`Server.MapPath` 方法与 `Href` 方法。

~ 运算符、Server.MapPath 与 Href 方法

`~` 运算符用于在服务器端代码中声明相对于当前 Web 应用程序根目录的虚拟路径(如 `var myImagesFolder = "~/images";`、`var myStyleSheet = "~/styles/StyleSheet.css";`)。即使站点未来被部署到不同的磁盘文件夹或子虚拟目录下,业务代码也无需修改。

`Server.MapPath` 方法负责把虚拟路径(如 `~/dataFile.txt` 或 `/index.html`)解析为操作系统文件系统可识别的完整物理路径(如 `C:\Documents\MyWebSites\Demo\dataFile.txt`)。凡是需要在服务器端直接读写磁盘数据文件时,都必须提供完整的物理路径(并严防 `..` 路径遍历越界)。关于读写文本数据文件的完整实例将在后续文件章节中展开。

`Href` 是 `WebPage` 对象提供的方法,用于把服务器端使用的 `~` 虚拟路径转换为浏览器可理解的 URL(浏览器本身无法解析 `~` 符号)。在 HTML 的 `<a>`、`<img>` 和 `<link>` 标签中写入 `href="@Href(myStyleSheet)"` 时,站点部署在根路径下会输出 `/Shared/Site.css`,部署在子应用 `/portal` 下则自动解析为 `/portal/Shared/Site.css`。在现代 ASP.NET Core 中,静态资源统一置于 `wwwroot/` 目录,服务器物理路径改由 `IWebHostEnvironment.ContentRootPath` / `WebRootPath` 拼接获取,模板中则使用 `Url.Content("~/...")` 或 Razor Tag Helper 原生支持 `~/`。

URL、服务器名称、虚拟路径与物理路径映射示例

路径概念示例值(中立演示路径)职责说明
URLhttps://example.com/html/html-tutorial.html浏览器用来定位并请求网站资源的完整统一资源定位符。
服务器名称EXAMPLE-WEB承载目标 Web 应用的宿主机或站点主机标识。
虚拟路径/html/html-tutorial.html相对于网站根目录 `/` 的逻辑路径,不受底层磁盘目录变动影响。
物理路径C:\MyWebSites\example\html\html-tutorial.html文件在服务器操作系统磁盘中的实际绝对路径,供服务端 I/O 使用。

离线校验 ~ 虚拟路径、Server.MapPath 越界拦截与 Href 浏览器 URL 转换

python · 阅读源码
"""Offline ASP.NET semantic verification lab for Chapter 06 (webpages-folders)."""
import json
from pathlib import PureWindowsPath

VERSION = "CPython 3.12.14 offline ASP.NET WebPages/Core semantic verifier (IIS/WebMatrix absent)"


def map_path(app_root: str, virtual_path: str) -> str:
    root = PureWindowsPath(app_root)
    rel = virtual_path
    if rel.startswith("~/"):
        rel = rel[2:]
    elif rel.startswith("/"):
        rel = rel[1:]
    parts = [p for p in rel.replace("\\", "/").split("/") if p and p != "."]
    if ".." in parts:
        raise ValueError("Path traversal outside application root is forbidden")
    return str(root.joinpath(*parts))


def href_resolve(app_base: str, virtual_path: str) -> str:
    base = app_base.rstrip("/")
    if virtual_path.startswith("~/"):
        return f"{base}/{virtual_path[2:]}"
    if virtual_path.startswith("/"):
        return virtual_path
    return f"{base}/{virtual_path}"


def case_tilde_virtual_paths():
    my_images_folder = "~/images"
    my_stylesheet = "~/styles/StyleSheet.css"
    root_a = r"C:\Documents\MyWebSites\Demo"
    root_b = r"D:\Deploy\PortalV2"
    expected = {
        "root_a_images": r"C:\Documents\MyWebSites\Demo\images",
        "root_b_css": r"D:\Deploy\PortalV2\styles\StyleSheet.css",
        "code_unchanged_on_move": True,
    }
    actual = {
        "root_a_images": map_path(root_a, my_images_folder),
        "root_b_css": map_path(root_b, my_stylesheet),
        "code_unchanged_on_move": my_images_folder.startswith("~/") and my_stylesheet.startswith("~/"),
    }
    return {
        "name": "tilde_virtual_paths",
        "summary": "验证 ~ 运算符定义应用根相对虚拟路径,在站点物理目录迁移后无需改动源码",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_server_mappath_and_traversal_guard():
    app_root = r"C:\Documents\MyWebSites\Demo"
    mapped_data = map_path(app_root, "~/dataFile.txt")
    mapped_appdata = map_path(app_root, "~/App_Data/Persons.txt")
    blocked = False
    try:
        map_path(app_root, "~/../secret.config")
    except ValueError:
        blocked = True
    expected = {
        "data_file": r"C:\Documents\MyWebSites\Demo\dataFile.txt",
        "app_data_file": r"C:\Documents\MyWebSites\Demo\App_Data\Persons.txt",
        "traversal_blocked": True,
    }
    actual = {
        "data_file": mapped_data,
        "app_data_file": mapped_appdata,
        "traversal_blocked": blocked,
    }
    return {
        "name": "server_mappath_and_traversal_guard",
        "summary": "模拟 Server.MapPath 将虚拟路径解析为服务器物理路径,并拦截越界路径遍历",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_href_browser_url_conversion():
    css_virtual = "~/Shared/Site.css"
    root_hosted = href_resolve("", css_virtual)
    subapp_hosted = href_resolve("/portal", css_virtual)
    link_tag = f'<link rel="stylesheet" type="text/css" href="{root_hosted}" />'
    expected = {
        "root_hosted": "/Shared/Site.css",
        "subapp_hosted": "/portal/Shared/Site.css",
        "link_tag": '<link rel="stylesheet" type="text/css" href="/Shared/Site.css" />',
        "no_tilde_in_html": True,
    }
    actual = {
        "root_hosted": root_hosted,
        "subapp_hosted": subapp_hosted,
        "link_tag": link_tag,
        "no_tilde_in_html": "~" not in link_tag,
    }
    return {
        "name": "href_browser_url_conversion",
        "summary": "模拟 WebPage.Href() 将 ~ 虚拟路径转换为浏览器可识别的根目录或子应用 URL",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_logical_folders_and_url_mapping():
    folders = {
        "Account": "登录与安全文件",
        "App_Data": "数据库与数据文件(禁止直接 HTTP 下载)",
        "Images": "网站图片资源",
        "Scripts": "浏览器端脚本",
        "Shared": "布局页与公共样式等共享文件",
    }
    mapping = {
        "URL": "https://example.com/html/html-tutorial.html",
        "ServerName": "EXAMPLE-WEB",
        "VirtualPath": "/html/html-tutorial.html",
        "PhysicalPath": map_path(r"C:\MyWebSites\example", "/html/html-tutorial.html"),
    }
    expected = {
        "folder_count": 5,
        "virtual_path": "/html/html-tutorial.html",
        "physical_path": r"C:\MyWebSites\example\html\html-tutorial.html",
    }
    actual = {
        "folder_count": len(folders),
        "virtual_path": mapping["VirtualPath"],
        "physical_path": mapping["PhysicalPath"],
    }
    return {
        "name": "logical_folders_and_url_mapping",
        "summary": "核对典型 ASP.NET 网站五大逻辑文件夹职责及 URL、服务器名、虚拟路径与物理路径映射关系",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_tilde_virtual_paths(),
        case_server_mappath_and_traversal_guard(),
        case_href_browser_url_conversion(),
        case_logical_folders_and_url_mapping(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器确认 ~ 路径可随站点根目录无感迁移、Server.MapPath 解析物理路径并拦截 .. 遍历、Href 正确处理根站点与子应用前缀,五大逻辑目录职责完整。
离线校验 ~ 虚拟路径、Server.MapPath 越界拦截与 Href 浏览器 URL 转换

所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。

当前源码 SHA256:4b7ab3e6b9ac1388c114ea17ee0761d2e76ca6467b9f9647970b18dfffba84b7

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载WebPages 文件夹实验

所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。

ZIP SHA256:0d4f7fd1184207bf6da96a9867c8c2e382595f69abfda790815277e0f66667f9

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 HTML 的 `<link href="...">` 中为什么不能直接写 `~/Shared/Site.css`,而要写成 `@Href("~/Shared/Site.css")`?

展开参考解答

因为 `~` 是 ASP.NET 服务器端特有的应用根符号,浏览器并不认识 `~`;经过 `@Href()` 转换后,服务器才会输出浏览器可请求的正确相对根路径(如 `/Shared/Site.css` 或带子应用前缀的路径)。

规范与官方依据