asp.net mvc routing and the mysterious 404
I am new to .net mvc. In a nutshell, I want to see my website so people can type: mywebsite/John@Eric and get processed by the correct controller.
On the other hand, I'd like to be able to also specify direct actions such as: mywebsite/GetPeople
and get proccessed by GetPeople action.
I have set up two routin开发者_StackOverflow中文版g rules in my application:
First Route
routes.MapRoute("Default",
"{id}",
new { controller = "Friends", action = "Index", id = UrlParameter.Optional },
new { controller = @"[^\.]*", id = @"(?i)[a-z]*@[a-z]*" }
);
Second Route
routes.MapRoute(
"Friends",
"{action}/{id}",
new { controller = "Friends" }
);
The first and default route works great, but then when I send a request like this: mywebsite/GetPeople the cheacky index action takes over and reads GetPeople as if it were a parameter. Even though I added my real awesome regax, this doesn't seem to work.
Any ideas ?
Here's how your routes might look:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Friends",
"{id}",
new { controller = "Friends", action = "Index", id = UrlParameter.Optional },
new { id = @"(?i)[a-z]*@[a-z]*" }
);
routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Friends", action = "Index", id = UrlParameter.Optional }
);
}
Now mywebsite/John@Eric
will be handled by the Index
action of the Friends
controller and mywebsite/GetPeople
will be handled by the GetFriends
action of the Friends
controller.
That is because of the way routing works in MVC. It just matches incoming URLs with routes in the order the routes are declared in RegisterRoutes. In this case the GetPeople in the URL would match with the Id parameter as everything is optional. To fix this, I would add a default as the last route. It could be done as so
routes.MapRoute("", "{controller}/{action}", new { controller = "Friends",action="Index" });
This would handle the GetMyPeople URL. You would need to have an Index action on it though. The MvcContrib has an excellent Test helper for testing out MVC routes before actually running it from the app. You can get the bits here
精彩评论