我希望生成以下网址
http://example.com/routes/A
和
http://example.com/routes/alpha-to-beta
对于此实现,我已向Global.asax
文件
routes.MapRoute(
"routes", // Route name
"routes/{routeName}", // URL with parameters
new { controller = "busroute", action = "SingleRoute" } // Parameter defaults
);
routes.MapRoute(
"alpharoutes", // Route name
"routes/{alphRoute}", // URL with parameters
new { controller = "busroute", action = "AlphabetRoute" } // Parameter defaults
);
但是,这不符合预期。点击链接将我带到第一个注册的操作。
请说明此实施有什么问题。
答案 0 :(得分:1)
您需要路线约束:
public class SingleCharacterConstraint: IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
if (!values.ContainsKey(parameterName))
return false;
var parameterValue = (string)values[parameterName];
return !string.IsNullOrWhitespace(parameterValue)
&& parameterValue.Length == 1;
}
}
然后重新排序地图,并添加约束:
routes.MapRoute(
"alpharoutes", // Route name
"routes/{alphRoute}", // URL with parameters
new { controller = "busroute", action = "AlphabetRoute" }, // Parameter defaults
new { alphRoute = new SingleCharacterConstraint() }, // Constraint
);
routes.MapRoute(
"routes", // Route name
"routes/{routeName}", // URL with parameters
new { controller = "busroute", action = "SingleRoute" } // Parameter defaults
);