[英]Create object from List elements
非常抱歉,标题可能不够翔实,但我不知道该如何解释我要在问题中尝试做的事情。
因此,我有一个MVC应用程序,并且正在从Web.config
的配置部分加载路由。
为了封装配置元素中所需的所有信息,我创建了一个RouteModel。
IEnumerable<RouteModel> configuredRoutes = RoutingFacade.GetAllRoutes();
foreach(RouteModel route in configuredRoutes)
{
routes.MapRoute(route.Name, route.Url,
new { controller = "Home", action = "Index", managers = route.Managers });
}
忽略那里的经理钥匙。
到目前为止还不错,但是我的问题是这个。
我的RouteModel
具有Constraints
属性,该属性返回具有该路由的所有已配置约束的List<ConstraintModel>
。
ConstraintModel
只有两个属性, Name
和Value
。
如您所知, MapRoute
方法采用一个附加的object
参数作为约束,该对象的构造如下:
new { constraint1 = value1, constraint2 = value2, .. }
如何将List<ConstraintModel>
变成类似的东西?
非常感谢您抽出宝贵的时间阅读我的问题,非常感谢
如果查看RouteCollection
类的方法,您会注意到这里有一个Add
方法( MSDN文章在此处 )。
您可以做的是调用它(这就是MapRoute
扩展方法最终完成的工作),并根据需要创建Route
类的实例。
Dictionary<string, object> constraints = new Dictionary<string, object>();
// populate your constraints into the constraints dictionary here..
Dictionary<string, object> dataTokens = new Dictionary<string, object>();
Dictionary<string, object> defaults = new Dictionary<string, object>();
Route route = new Route(" << url >> ", new MvcRouteHandler())
{
Constraints = new RouteValueDictionary(constraints),
DataTokens = new RouteValueDictionary(),
Defaults = new RouteValueDictionary()
};
routes.Add(route);
这样,您就有机会为约束指定string
- object
对。
编辑
此外,如果您对如何使用此方法有任何疑问,但对MapRoute
扩展方法有什么了解,我建议您使用ILSpy来反汇编定义MapRoute
的程序集(即System.Web.Mvc.dll
),然后转到一步一步地发现MapRoute
和RouteCollection.Add
之间的连接。
编辑2-关于路线名称
您还可以检查重载RouteCollection.Add(string name, RouteBase item)
。 这是您可以指定路线名称的一种方式。
所以基本上您可以执行以下操作:
routes.Add(" My route with dynamically loaded constraints ", route);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.