ASP.NET MVC routing conflict - null value for input variable

不羁的心 提交于 2019-12-05 07:57:15

The problem with your example is that the match is happening on the first route and it's seeing "5" as the username parameter. You can use constraints to limit what values are accepted for each parameter to accomplish what you're wanting. Since the "Default" route that accepts an Id is more restrictive than the "CustomerView" route, I would list the "Default" route first with a constraint on the Id parameter:

routes.MapRoute(
    "Default", "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "0" },
    new { id = @"\d+" } 
    );

This will cause the first route to only match if Id is an integer value. All other requests would then fall through to the "CustomerView" route that would pick up any other requests that didn't have integers as that third parameter.

Check out Creating a Route Constraint for an explanation of constraints.

My (admittedly limited) understanding so far was that, if a variable name specified in a route matches that specified in a controller action definition, it will assume that one regardless of order.

The binding of route values to action arguments happens AFTER the framework determines which route to use. Route selection is performed using a "first match wins" heuristic: the first route that can successfully match the incoming request is used, even if a "better" route was defined later.

Michael's solution is correct. You need to list the Default route first, using route constraints to only match URLs where the ID is numeric. Your second, less restrictive route should come next.

NOTE: If you follow Michael's solution you'll run into problems if you have any users with a username consisting only of numbers. You might consider adding some other discriminating factor to the routes, like putting the keyword "user" in the 2nd one:

routes.MapRoute(
    "Default", "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "0" },
    new { id = @"\d+" } 
 );

routes.MapRoute(
    "CustomerView", "{controller}/{action}/user/{username}",
    new { controller = "Home", action = "Index", username = "" }
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!