【问题标题】:URL Rewriting on my ASP .NET MVC website我的 ASP .NET MVC 网站上的 URL 重写
【发布时间】:2012-12-25 09:56:58
【问题描述】:

我正在开发一个图像查看器,所以我有一个名为 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

我尝试在RouteConfig 类的RegisterRoutes 方法中做一些技巧,但我无法得到之前的结果。

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

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

非常感谢!

【问题讨论】:

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


    【解决方案1】:

    您需要将更具体的路由放在默认路由之前,因为路由的评估顺序与您声明它们的顺序相同:

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

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 2011-01-23
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      相关资源
      最近更新 更多