我正在处理一个图像查看器,所以我有一个名为Viewer
的控制器,当我传递它routeValues
时,它会像这样在URL中传递:
http://www.mywebsite.com/Viewer?category=1&image=2
以下是此页面上的链接:
@Url.Action("Index", new { category = p.Category, image = p.Image })
但我喜欢这个网址: http://www.mywebsite.com/Viewer/1/2
我试图在RegisterRoutes
类的RouteConfig
方法中做一些技巧,但我无法获得之前的结果。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Viewer",
url: "{controller}/{action}/{category}-{image}",
defaults: new { controller = "Viewer", action = "Index", category = 1, image = 1 }
);
}
}
有谁知道我可以在哪里做到这一点?
非常感谢!
答案 0 :(得分:3)
您需要在默认路由之前放置更具体的路由,因为路由的评估顺序与您声明的路径相同:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Viewer",
url: "{controller}/{action}/{category}/{image}",
defaults: new { controller = "Viewer", action = "Index", category = 1, image = 1 }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}