gzak
gzak

Reputation: 4110

Twitter-like routes in ASP.NET MVC 2 application

I'd like to have routes set up as follows:

xyz/ maps to one action method with no parameters, but xyz/{username} maps to a different action (in the same controller or not, doesn't matter) that takes an argument called username of type string. Here are my routes so far:

routes.MapRoute(
    "Me",
    "Profile",
    new { controller = "Profile", action = "Me" }
);

routes.MapRoute(
    "Profile",
    "Profile/{username}",
    new { controller = "Profile", action = "Index" }
);

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

Currently, if I navigate to /Profile/someuser, the Index action in the Profile controller is hit as expected. But if I navigate to /Profile/ or /Profile, I get 404.

What gives?

Upvotes: 4

Views: 317

Answers (1)

Bertrand Marron
Bertrand Marron

Reputation: 22210

It works fine for me. I suppose you do not have a Me action method in your Profile controller?

I tried with the following routes:

routes.MapRoute(
    "Me",
    "Profile",
    new { controller = "Home", action = "Me" }
);

routes.MapRoute(
    "Profile",
    "Profile/{username}",
    new { controller = "Home", action = "Index" }
);

With the Index and Me action methods defined like this :

public ActionResult Index(string username) {
   ViewData["Message"] = username;
   return View();
}

public ActionResult Me() {
   ViewData["Message"] = "this is me!";
   return View( "Index" );
}

I used the default Home/Index view.

Upvotes: 4

Related Questions