ASP.NET 路由系統不僅處理輸入請求的路由解析,也支援根據註冊路由規則生成輸出 URL。前者依賴 RouteCollection.GetRouteData,後者則透過 GetVirtualPathData 實現。為了方便開發,ASP.NET MVC 提供了 HtmlHelper 與 UrlHelper 兩大輔助類別,分別用於生成超連結(ActionLink/RouteLink)與純 URL(Action/RouteUrl),底層皆呼叫 GetVirtualPathData。
UrlHelper 封裝 RequestContext 與 RouteCollection:
public class UrlHelper
{
public UrlHelper(RequestContext requestContext);
public UrlHelper(RequestContext requestContext, RouteCollection routeCollection);
public RequestContext RequestContext { get; }
public RouteCollection RouteCollection { get; }
}
HtmlHelper 則透過 ViewContext 取得請求上下文與路由資料:
public class HtmlHelper
{
public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer);
public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection);
public RouteCollection RouteCollection { get; }
public ViewContext ViewContext { get; }
}
UrlHelper.Action 多載支援指定 Action、Controller、路由值、協定與主機名,若指定協定則回傳完整 URL,否則為相對 URL。HtmlHelper.ActionLink 則生成完整的 <a> 標籤,其目標 URL 生成邏輯與 UrlHelper 一致。
public static class LinkExtensions
{
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName);
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
// ... 其他多載
}