升级到.NET 4后,为什么GetVirtualPath失败

Sam*_*ron 8 .net-4.0 .net-3.5 asp.net-mvc-2

我定义了以下路线:

 var route = new Route("{id}/{a}/{b}", new MvcRouteHandler());
 route.Defaults = new RouteValueDictionary(new { controller = "Home", action = "Show" });
 route.Defaults.Add("a", "");
 route.Defaults.Add("b", "");
Run Code Online (Sandbox Code Playgroud)

以下控制器代码:

public ActionResult Show(int id)
{
    RouteValueDictionary routeValues = new RouteValueDictionary();
    routeValues["Controller"] = "Home";
    routeValues["Action"] = "Show";
    routeValues["id"] = 1;
    var requestContext = new RequestContext(this.HttpContext, RouteData);
    var rv = route.GetVirtualPath(requestContext, routeValues);
    // when targetting .NET 4 rv is null, when its 3.5 it is "/1"

 }
Run Code Online (Sandbox Code Playgroud)

为什么这段代码在.NET 3.5中返回路由而不在.NET 4.0中?

Asb*_*erg 1

你为什么要在你的路线中混合aandbControllerand Action?由于ControllerAction是路由引擎所必需的,因此我建议您坚持使用它们。以下示例有效:

var route = new Route("{Id}/{Controller}/{Action}", new MvcRouteHandler())
{
  Defaults = new RouteValueDictionary
  {
    { "Id", "" },
    { "Controller", "Home" },
    { "Action", "Show" },
  }
};

ActionResult Show(int id)
{
  RouteValueDictionary routeValues = new RouteValueDictionary();
  routeValues["Controller"] = "Home";
  routeValues["Action"] = "Show";
  routeValues["Id"] = 1;
  var requestContext = new RequestContext(this.HttpContext, RouteData);
  var rv = route.GetVirtualPath(requestContext, routeValues);
  // rv.VirtualPath == "1".
}
Run Code Online (Sandbox Code Playgroud)