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

时间:2010-08-24 01:59:18

标签: .net-3.5 asp.net-mvc-2 .net-4.0

我定义了以下路线:

 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", "");

以下控制器代码:

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"

 }

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

1 个答案:

答案 0 :(得分:1)

为什么在您的路线中将abControllerAction混合在一起?由于路由引擎需要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".
}