从List元素创建对象

时间:2014-04-24 13:31:58

标签: c# asp.net .net asp.net-mvc visual-studio

我很抱歉标题可能不够丰富,但我不知道如何解释我在一个问题中想要做什么。

所以,我有一个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只有两个属性,NameValue

您可能知道,MapRoute方法需要额外的object参数作为约束,此对象的构造如下:

new { constraint1 = value1, constraint2 = value2, .. }

如何将List<ConstraintModel>变成类似的东西?

我真的很感谢你花时间阅读我的问题,非常感谢你提前

1 个答案:

答案 0 :(得分:4)

如果您查看RouteCollection课程的方法,您会注意到Add方法(MSDN article here)。

你可以做的是你可以调用它(这是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来反汇编定义{{1}的程序集} {(MapRoute)并一步一步地发现System.Web.Mvc.dllMapRoute之间的联系。

编辑2 - 关于路线名称

您还可以检查重载RouteCollection.Add。 这是您可以指定路线名称的一种方式。

所以基本上你可以这样做:

RouteCollection.Add(string name, RouteBase item)