CMS 页面的 MVC 路由

MVC routing for CMS pages

我正在使用 MVC 5 创建一个 CMS 的精简版本,我正在尝试解决路由方面的问题。

我需要处理带有 /how-it-works//about-us/ 等 url 的页面,因此内容在这些路径上键入。

在我的 RouteConfig 文件中,我使用 'catch all' 路由如下::

routes.MapRoute("Static page", "{*path}", new { controller = "Content", action = "StaticPage" });

这成功命中了我正在寻找的控制器操作,但是这意味着对实际存在的控制器操作的请求(例如 /navigation/main 也会沿着这条路线发送)。

我知道我可以有一个匹配 /navigation/main 的路由,但是我宁愿将 MVC 配置为默认执行此操作,就像我不添加上面的规则时一样,任何想法?

将您的 "catch all" 路线添加到 "default" 路线之上,然后将 route constrain 添加到这样的路径中:

public class RouteConfig
{
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                "Static page", 
                 "{*path}", 
                 new { controller = "Content", action = "StaticPage" }
                 new { path = new PathConstraint() });

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional });
       }
}

PathConstraint 应该从 IRouteConstraint 接口派生,可以是这样的:

public class PathConstraint: IRouteConstraint
{        

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (values[parameterName] != null)
            {
                var permalink = values[parameterName].ToString();
                //gather all possible paths from database 
                //and check if permalink is any of them 
                //return true or false
                return database.GetPAths().Any(p => p == permalink);
            }
            return false;
        }
    }

因此,如果 "path" 不是您的页面路径之一,则不会满足 PathConstrain 并且 "Static page" 路由将被跳过并传递到下一个路由。