我定义了以下路线:
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中返回?
答案 0 :(得分:1)
为什么在您的路线中将a
和b
与Controller
和Action
混合在一起?由于路由引擎需要Controller
和Action
,因此我建议您坚持使用它们。以下示例有效:
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".
}