首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET 實現無副檔名友好 URL (URL Rewriting / Routing) 完全指南

     編輯:程式設計綜合問答

需求

訪問 www.xxx.com/welcome 實際執行 welcome.aspx,同理 /product → product.aspx,隱藏 .aspx 後綴,實現 REST 風格友好 URL。

方案對比

| 方案 | 適用版本 | 複雜度 | 靈活性 | 推薦指數 | |------|----------|--------|--------|----------| | **ASP.NET Routing (Web Forms 4.0+)** | .NET 4.0+ | 低 | 高 | ⭐⭐⭐⭐⭐ | | **URL Rewrite Module (IIS 7+)** | IIS 7+ | 中 | 高 | ⭐⭐⭐⭐ | | **ASP.NET MVC / Core** | 新項目 | 高 | 最高 | ⭐⭐⭐⭐⭐ | | **Default Document + 目錄結構** | 所有版本 | 低 | 低 (僅首頁) | ⭐ |

方案一:ASP.NET Routing (Web Forms 原生,零依賴)

Global.asax.cs

using System.Web.Routing;

public class Global : System.Web.HttpApplication {
    void Application_Start(object sender, EventArgs e) {
        RegisterRoutes(RouteTable.Routes);
    }

    void RegisterRoutes(RouteCollection routes) {
        // 忽略 .axd 等資源
        routes.Ignore("{resource}.axd/{*pathInfo}");

        // 映射規則:/welcome -> ~/welcome.aspx
        routes.MapPageRoute("WelcomeRoute", "welcome", "~/welcome.aspx");
        routes.MapPageRoute("ProductRoute", "product", "~/product.aspx");
        routes.MapPageRoute("AboutRoute", "about", "~/about.aspx");

        // 通用規則 (可選):/{page} -> ~/{page}.aspx
        // routes.MapPageRoute("DynamicRoute", "{page}", "~/{page}.aspx", 
        //     false, new RouteValueDictionary { { "page", "welcome" } });
    }
}

頁面中生成連結:Page.GetRouteUrl("WelcomeRoute", null) 或 ResolveUrl("~/welcome")。

方案二:IIS URL Rewrite Module (不改代碼,僅配置)

安裝 URL Rewrite 2.0+,在 web.config 中:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="HideAspxExtension" stopProcessing="true">
        <match url="^(.*)$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_FILENAME}.aspx" matchType="IsFile" />
        </conditions>
        <action type="Rewrite" url="{R:1}.aspx" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

效果:/welcome → 內部重寫到 /welcome.aspx,瀏覽器地址欄保持 /welcome。

方案三:遷移至 ASP.NET Core (長期最佳)

// Program.cs / Startup.cs
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Welcome}/{id?}");
// 對應 Controllers/HomeController.cs -> public IActionResult Welcome() => View();

常見坑點

  • PostBack URL 錯誤:Web Forms 頁面 <form runat="server"> 的 action 會自動變回 .aspx。解決:form.Action = Request.RawUrl; 在 Page_Load 中設置。
  • 資源路徑:CSS/JS/圖片使用 ResolveUrl("~/Content/style.css") 或根路徑 /Content/style.css。
  • 驗證/授權:web.config <location path="welcome"> 需匹配路由 URL 而非物理文件。

總結建議

  1. 舊 Web Forms 項目:優先用 ASP.NET Routing (MapPageRoute),代碼可控、無額外組件。
  2. 不想動代碼/快速上線:裝 IIS URL Rewrite 配置 web.config。
  3. 新項目/重構:直接上 ASP.NET Core MVC/Razor Pages,原生支持 RESTful 路由。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved