【问题标题】:ASP.NET MVC3 Route Mapping reduction helpASP.NET MVC3 Route Mapping 减少帮助
【发布时间】:2011-07-31 16:58:16
【问题描述】:

我试图在我的 ASP.NET MVC3 应用程序中使用路由并尝试减少我的一些映射代码。我正在尝试在我的应用程序中跨多个不同实体使用一个通用的用户控制器/视图。例如,您有商店和公司,每个都有自己的用户集。有什么办法可以减少以下两条路线:

        routes.MapRoute(
            "StoreUsers", // Route name 
            "Store/Details/{entityID}/User/Index", // URL with parameters
            new { controller = "User", action = "StoreIndex"} // Parameter defaults
        );

        routes.MapRoute(
            "CompanyUsers", // Route name 
            "Company/Details/{entityID}/User/Index", // URL with parameters
            new { controller = "User", action = "CompanyIndex"} // Parameter defaults
        );

类似这样的东西?

        routes.MapRoute(
            "EntityUsers", // Route name 
            "{entity}/Details/{entityID}/User/Index", // URL with parameters
            new { controller = "User", action = entity + "Index"} // Parameter defaults
            new { entity = "(Store|Company)" } //Parameter constraints
        );

并将 {action} 参数(和 {action} 默认值)设置为:{entity} + "Index",因此它可以用于匹配约束的实体实体。

我在这里只将 2 条路由减少到 1 条,但我真正的问题不仅仅涉及这两个实体,如果我能让它工作,我可以将它用于必须模仿相同功能和其他功能的其他控制器操作(创建、编辑等)。

谢谢

【问题讨论】:

    标签: asp.net-mvc-3 routing


    【解决方案1】:

    我认为答案必须在那里,我只是没有寻找正确的东西,我搜索了 StackOverflow 并找到了这个帮助我开发解决方案的问题:

    asp.net mvc complex routing for tree path

    我可以设置如下所示的路线:

            routes.MapRoute(
                "EntityUsers", // Route name 
                "{entity}/Details/{entityID}/{controller}/{subaction}/{id}", // URL with parameters
                new {controller = "User", subaction = "Index", id = UrlParameter.Optional}, // Parameter defaults
                new {entity = "(Lender|Dealer)", controller="User"}
            ).RouteHandler = new UserRouteHandler();
    

    UserRouteHandler 类如下所示:

    public class UserRouteHandler : IRouteHandler {
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            string entity = requestContext.RouteData.Values["entity"] as string;
            string subaction = requestContext.RouteData.Values["subaction"] as string;
            if (entity != null && subaction != null)
            {
                requestContext.RouteData.Values["action"] = entity + subaction;
            }
            return new MvcHandler(requestContext);
        }
    }
    

    最后,我把问题复杂化了,不需要这个,但很高兴知道你可以拥有这种灵活性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 2011-10-11
      相关资源
      最近更新 更多