0

我正在使用图像查看器,所以我有一个名为的控制器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 }
        );
    }
}

有谁知道我在哪里可以做到这一点?

非常感谢 !

4

1 回答 1

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 }
        );
    }
}
于 2012-12-25T10:23:53.587 回答