Reputation: 14219
I don't know why I constantly struggle with this, but can someone explain why this doesn't work?
/
redirects to the index
action of the home
controller.
/gallery/
throws a 404 not found error.
/gallery/index
redirects to the index
action of the gallery
controller.
From the documentation:
When you define a route, you can assign a default value for a parameter. The default value is used if a value for that parameter is not included in the URL. You set default values for a route by assigning a dictionary object to the Defaults property of the Route class.
I don't understand how this doesn't follow that rule:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
To me it reads:
controller
is not defined, use Home
.action
is not defined, use Index
.gallery
and an action is not included in the URL so it should be going to the Index
.Am I missing something or this unnecessarily confusing and silly?
I've always found MVC3 routing problematic but accepted it. Then I started playing with Rails and Node frameworks and they have ridiculously simple routing so now .NET MVC just annoys me when it doesn't work or makes me use convoluted patterns.
For reference in case someone asks, my Gallery controller, Action and View are all defined and working when I browse to /gallery/index
.
public class GalleryController : Controller
{
public ActionResult Index()
{
return View();
}
}
Upvotes: 1
Views: 273
Reputation: 14219
Problem was I had a hidden directory (not included in my solution) with the same name as my faulty route: /gallery
.
Luckily I'm too tired this morning to punch my monitor.
Thanks everyone for your suggestions, all +1'd for helpful guidance.
PS. To help me investigate the problem I used Phil Haack's routing debugger.
Upvotes: 1
Reputation: 1038820
You definitively oughta be doing something wrong or there is some code you haven't shown us. Perform the following steps:
Replace the contents of HomeController.cs
with this:
public class HomeController : Controller
{
public ActionResult Index()
{
return Content("home/index");
}
}
public class GalleryController : Controller
{
public ActionResult Index()
{
return Content("gallery/index");
}
}
Hit F5
Here's what happens:
requested url | result
-----------------+---------------
/ | home/index
/home | home/index
/home/ | home/index
/home/index | home/index
/home/index/ | home/index
/gallery | gallery/index
/gallery/ | gallery/index
/gallery/index | gallery/index
/gallery/index/ | gallery/index
Exactly as expected, isn't it?
Upvotes: 5