简体   繁体   English

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

[英]URL Rewriting on my ASP .NET MVC website

I'm working on an image viewer, so I've a controller named Viewer and when I pass it routeValues it is passed in the URL like this : http://www.mywebsite.com/Viewer?category=1&image=2 我正在使用图像查看器,因此我有一个名为Viewer的控制器,当我将其传递给routeValues它会通过以下URL传递: http : routeValues =2

Here is the link used to get on this page : 这是进入此页面的链接:

@Url.Action("Index", new { category = p.Category, image = p.Image })

But I do like to have this URL : http://www.mywebsite.com/Viewer/1/2 但我确实希望拥有此URL: http : //www.mywebsite.com/Viewer/1/2

I have tried to do a few tricks in the RegisterRoutes method of the RouteConfig class but I can not get the previous result. 我试图在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 }
        );
    }
}

Does anyone know where I can do this? 有人知道我在哪里可以做吗?

Thanks a lot ! 非常感谢 !

You need to put your more specific route before the default route, because the routes are evaluated in the same order in which you declared them: 您需要将更具体的路由放在默认路由之前,因为路由的评估顺序与声明它们的顺序相同:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM