Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is GetVirtualPath failing after upgrading to .NET 4

I have the following route defined:

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

And the following controller code:

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"

 }

Why does this code return a route in .NET 3.5 and not in .NET 4.0?

like image 344
Sam Saffron Avatar asked Aug 24 '10 01:08

Sam Saffron


1 Answers

Why are you mixing a and b with Controller and Action in your route? Since Controller and Action are required by the routing engine, I suggest you stick with them. The following example works:

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".
}
like image 176
Asbjørn Ulsberg Avatar answered Dec 02 '22 08:12

Asbjørn Ulsberg