Search code examples
asp.netasp.net-mvcurl-rewritingurl-routingmaproute

URL rewriting using similar MapRoutes


I have 2 similar maproute requests but I'm trying to target different routes.

Basically I'm creating a picture project using ASP.NET MVC.

What I want is to have the URL as:

website.com/pictures/username

and

website.com/pictures/pictureid

I'm using this as the map routes atm. Hoped that the different signatures would be enough to distinguish which action i would need.

The pictures controller has the action methods as ActionResult Index (string username) { ... } ActionResult Index (long id) { ... }

routes.MapRoute(
    "UsersPicturesRoute",
    "Pictures/{username}",
    new { controller = "Pictures", action = "Index", username = UrlParameter.Optional }
);

routes.MapRoute(
    "SinglePictureRoute",
    "Pictures/{id}",
    new { controller = "Pictures", action = "Index", id = UrlParameter.Optional }
);

Is there a way to have this desired outcome?


Solution

  • You can change your RegisterRoutes in below sequence then you will get your required output

    routes.MapRoute(
              "SinglePictureRoute",
              "Pictures/{id}",
              new { controller = "Home", action = "abcd", id = UrlParameter.Optional },
              new { id = @"\d+" } // Parameter constraints
          );
    
    routes.MapRoute(
             "UsersPicturesRoute",
             "Pictures/{username}",
             new { controller = "Home", action = "abcTest", username = UrlParameter.Optional }
         );