如何动态添加到 ASP.NET MVC RouteTable?

jon*_*ell 5 asp.net-mvc routes routetable

我们的网站上有一个区域,人们可以在其中注册并在我们想要托管的网站上获得自己的页面 ~/ pageSlug。我尝试使用 Global.asax 中的规则来执行此操作,但这破坏了允许 ~/ Controller直接映射到 Index 操作的基本默认路由。我不允许在 userSlug 前面放置任何类型的分隔符,因此 ~/p/ pageSlug在这里并不是真正的选项。

在将用户页面添加到路由方面,我循环浏览 App_Start 处的页面并将它们显式添加到 RoutesTable 中。这工作正常,并且我们已经将 AppPool 刷新设置得足够长,使其成为每天一次的任务。这确实给我们留下了 24 小时的时间来为我们的用户“让页面上线”,这是我正在努力解决的问题。

理想情况下,我想要做的是在用户注册后将相关路由动态添加到 RouteTable。我尝试这样做:

RouteTable.Routes.Add(
    RouteTable.Routes.MapRoute(
        toAdd.UrlSlug + "Homepage", 
        toAdd.UrlSlug, 
        new { controller = "Controller", View = "View", urlSlug = toAdd.UrlSlug }
    )
);
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用。我在其他地方找不到解决方案,而且我确信我的代码非常幼稚,而且暴露出对路由缺乏了解 - 请帮忙!

Gbo*_*man 5

如果您尝试使用路由约束会怎么样?获取所有用户的列表并限制所选路由以匹配该列表中的条目

public class UserPageConstraint : IRouteConstraint
{
    public static IList<string> UserPageNames = (Container.ResolveShared<IUserService>()).GetUserPageNames();

    bool _IsUserPage;
    public UserPageConstraint(bool IsUserPage)
    {
        _IsUserPage = IsUserPage;            
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (_IsUserPage)
            return UserPageNames.Contains(values[parameterName].ToString().ToLower());
        else
            return !UserPageNames.Contains(values[parameterName].ToString().ToLower());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在Global.asax.cs中为用户设置路由,如下所示:

routes.MapRoute("UserHome", "{userPage}", new { controller = "UserPageController", action = "Index" }, new { userPage = new UserPageConstraint(true) });
Run Code Online (Sandbox Code Playgroud)

对于上面的路由,在 UserPageController 的操作“index”中,我们将 userPage 作为参数。

对于相对于userPage Home的其他路由,我们可以相应地添加路由。例如,userdetails页面路由可以添加如下:

routes.MapRoute("UserHome", "{userPage}/mydetails", new { controller = "UserPageController", action = "Details" }, new { userPage = new UserPageConstraint(true) });
Run Code Online (Sandbox Code Playgroud)

你可以试试这个看看。


Jak*_*cki 0

我不认为你可以动态添加路线。

看看这个问题,也许会对你有帮助: ASP.NET MVC custom Routing for search