当您查看操作链接的源代码时,您会发现
<%= Html.ActionLink("LinkText", "Action", "Controller"); %>
将匹配
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName) {
return ActionLink(htmlHelper, linkText, actionName, controllerName, new RouteValueDictionary(), new RouteValueDictionary());
}
现在到目前为止,这看起来不错,因为它正在创建一个新的路由值字典,因此它不会传递当前上下文中的值以添加到新链接,这就是将要发生的情况。
然而,在生成 url 的代码中:
public static string GenerateUrl(string routeName, string actionName, string controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues) {
if (routeCollection == null) {
throw new ArgumentNullException("routeCollection");
}
if (requestContext == null) {
throw new ArgumentNullException("requestContext");
}
RouteValueDictionary mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, requestContext.RouteData.Values, routeValues, includeImplicitMvcValues);
VirtualPathData vpd = routeCollection.GetVirtualPathForArea(requestContext, routeName, mergedRouteValues);
if (vpd == null) {
return null;
}
string modifiedUrl = PathHelpers.GenerateClientUrl(requestContext.HttpContext, vpd.VirtualPath);
return modifiedUrl;
}
你可以看到 requestContext 被引用,它可以访问routeData和routeCollections,其中将包含id数据。创建 VirtualPathForArea 时,以下行是 id 值出现在 url 中的位置:
internal static VirtualPathData GetVirtualPathForArea(this RouteCollection routes, RequestContext requestContext, string name, RouteValueDictionary values, out bool usingAreas) {
if (routes == null) {
throw new ArgumentNullException("routes");
}
if (!String.IsNullOrEmpty(name)) {
// the route name is a stronger qualifier than the area name, so just pipe it through
usingAreas = false;
return routes.GetVirtualPath(requestContext, name, values);
}
string targetArea = null;
if (values != null) {
object targetAreaRawValue;
if (values.TryGetValue("area", out targetAreaRawValue)) {
targetArea = targetAreaRawValue as string;
}
else {
// set target area to current area
if (requestContext != null) {
targetArea = AreaHelpers.GetAreaName(requestContext.RouteData);
}
}
}
// need to apply a correction to the RVD if areas are in use
RouteValueDictionary correctedValues = values;
RouteCollection filteredRoutes = FilterRouteCollectionByArea(routes, targetArea, out usingAreas);
if (usingAreas) {
correctedValues = new RouteValueDictionary(values);
correctedValues.Remove("area");
}
VirtualPathData vpd = filteredRoutes.GetVirtualPath(requestContext, correctedValues);
return vpd;
}
该行:
VirtualPathData vpd = filteredRoutes.GetVirtualPath(requestContext, correctedValues);
获取虚拟路径(这只是路由)并返回它。所以虚拟路径是/Home/About/Flib
然后,当返回该虚拟路径时,以下行使用它来设置操作链接的客户端 URL:
string modifiedUrl = PathHelpers.GenerateClientUrl(requestContext.HttpContext, vpd.VirtualPath);
因此,看起来 actionlink 似乎是使用该区域的虚拟路径设置的,这只是匹配的路由,在本例中恰好是默认路由。