【问题标题】:ASP.Net MVC 4/5 - Refresh routing at runtimeASP.Net MVC 4/5 - 在运行时刷新路由
【发布时间】:2018-06-02 17:45:17
【问题描述】:

在基于 MVC 的内容管理系统中,用户可以在运行时创建新页面并为页面指定 slug。

我在 application_startup 注册了这些 slugs/routes,效果很好:

foreach (var slug in pagesSlugs)
        {
            routes.MapRoute(
                name: $"Page-{slug}",
                url: $"{slug}",
                defaults: new { controller = "Page", action = "Details", slug = slug }
            );
        }

当用户创建新页面时,如何在运行时重新运行 RegisterRoutes?

注意:

由于用户可以创建任何 slug,我无法创建具有模式的动态路由,例如 /pages/{slug}。

【问题讨论】:

    标签: .net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5


    【解决方案1】:

    你不需要在运行时添加新的路由,事实上你应该只为你的 'slug' 设置一个路由,但是添加一个路由约束来查找你的用户的 slug 表。如果它匹配到数据库中的一个值,那么它将执行该路由,否则它将落到下一个匹配的路由。

    routes.MapRoute(
        name: "Page",
        url: "{slug}",
        defaults: new { controller = "Page", action = "Details" }
        constraints: new { slug = new SlugConstraint() }
    )
    
    public class SlugConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            IEnumerable<string> slugs = ... // your code to get the slugs
            // Get the slug from the url
            var slug  = values["slug"].ToString().ToLower();
            // Check for a match (assumes case insensitive)
            return slugs.Any(x => x.ToLower() == slug);
        }
    }
    

    由于这将在每个请求中调用,因此您应该考虑缓存 slug(例如在 MemoryCache 中),并且每次用户创建新页面时,使缓存无效并再次从数据库中刷新。

    【讨论】:

    • 非常好,这比在启动时生成路线更容易管理。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 2014-05-25
    • 2015-12-09
    • 2015-04-06
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多