问题
I have currently the following routes:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.gif/{*pathInfo}");
MvcRoute.MappUrl("{controller}/{action}/{ID}")
.WithDefaults(new { controller = "home", action = "index", ID = 0 })
.WithConstraints(new { controller = "..." })
.AddWithName("default", routes)
.RouteHandler = new MvcRouteHandler();
MvcRoute.MappUrl("{title}/{ID}")
.WithDefaults(new { controller = "special", action = "Index" })
.AddWithName("view", routes)
.RouteHandler = new MvcRouteHandler();
The SpecialController has a method: public ActionResult Index(int ID)
Whenever I point my browser to http://hostname/test/5
, I get the following error:
The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'SpecialController'. To make a parameter optional its type should be either a reference type or a Nullable type.
Parameter name: parameters
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Why is that? I used the mvccontrib route debugger, and it seems that the route is accessible as expected.
回答1:
It's exactly as the error message says. You've got a parameter called "ID" which has no default value, but your method is expecting a non-nullable int. Because there is no default value, it's trying to pass in a "null", but... it can't, because your int parameter is non-nullable.
The route debugger probably doesn't check types for nullable.
To fix it:
MvcRoute.MappUrl("{title}/{ID}")
.WithDefaults(new { controller = "special", action = "Index", ID = 0 })
.AddWithName("view", routes)
.RouteHandler = new MvcRouteHandler();
回答2:
I think you should put your custom route before the default one.
http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
回答3:
I propose the solution was your route variable names did not match your action parameter names.
// Global.asax.cs
MvcRoute.MappUrl("{controller}/{action}/{ID}")
.WithDefaults(new { controller = "home", action = "index", ID = 0 })
.WithConstraints(new { controller = "..." })
.AddWithName("default", routes)
.RouteHandler = new MvcRouteHandler();
This would work:
// Controller.cs
public ActionResult Index(int ID){...}
Where this wouldn't:
// Controller.cs
public ActionResult Index(int otherID) {...}
来源:https://stackoverflow.com/questions/1182768/asp-net-mvc-routing-trying-to-have-a-name-in-the-url