ggobbe
ggobbe

Reputation: 171

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

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

I have tried to do a few tricks in the RegisterRoutes method of the RouteConfig class but I can not get the previous result.

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 !

Upvotes: 0

Views: 900

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039558

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

Upvotes: 3

Related Questions