在我的ASP .NET MVC网站上重写URL

时间:2012-12-25 09:56:59

标签: c# asp.net asp.net-mvc-3 routevalues

我正在处理一个图像查看器,所以我有一个名为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 }
        );
    }
}

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

非常感谢!

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 }
        );
    }
}