【发布时间】:2012-11-05 14:08:07
【问题描述】:
作为this question 的后续,我正在尝试实现自定义路由约束,以便为特定路由动态修改RouteValueDictionary。
我已经完成了 95%:我可以根据提供的参数模式匹配任何路由,匹配 url 中指定的操作。此过程的最后一步是覆盖 RouteValueDictionary 以将键重命名为控制器操作的适当参数。
这是我的代码的相关sn-p(整个类将近300行,所以我不想全部添加,但如果需要我可以):
public class CustomRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string paramName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection.Equals(RouteDirection.UrlGeneration)) {
return false;
}
//this will grab all of the "actual" parameters out of the RVD, excluding action and controller
Dictionary<string, object> unMappedList = values.Where(x => x.Key.Contains("param")).OrderBy(xi => xi.Key).ToDictionary(
kvp => kvp.Key, kvp => kvp.Value);
string controller = values["controller"] as string;
string action = values["action"] as string;
//this method tries to find the controller using reflection
Type cont = TryFindController(controller);
if (cont != null) {
MethodInfo actionMethod = cont.GetMethod(action);
if (actionMethod != null) {
ParameterInfo[] methodParameters = actionMethod.GetParameters();
//this method validates that the parameters of the action that was found match the expected parameters passed in the custom constraint; it also performs type conversion
if (validateParameters(methodParameters, unMappedList)) {
for (int i = 0; i < methodParameters.Length; i++) {
values.First(x => x.Key == unMappedList.ElementAt(i).Key).Key = methodParameters.ElementAt(i).Name;
//above doesn't work, but even if it did it wouldn't do the right thing
return true;
}
}
}
}
return false;
}
}
这是我使用自定义约束的方式:
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{param1}-{param2}",
defaults: new { controller = "Admin", action = "Index" },
constraints: new { lang = new CustomRouteConstraint(new RoutePatternCollection( new List<ParamType> { ParamType.INT, ParamType.INT })) }
);
(我传递给构造函数的基本上是说“要查找的参数模式是两个整数”。所以当调用Match方法时,如果url中指定的动作有两个,它将返回true两个整数参数,与实际参数名称无关。)
那么,有没有办法可以覆盖此请求的 RouteValueDictionary?还是有其他我想念的方法可以做到这一点?
【问题讨论】:
-
不是 ASP.NET MVC 方面的专家,但我想知道路由字典是否是共享资源,是 C# 中的
static还是 VB.NET 中的Shared?如果是这样,那么您可能需要在修改它时使用锁定,因为其他请求可能会在您更改它的同时尝试读取它。
标签: c# asp.net-mvc routes asp.net-mvc-routing