解决方法
这是一个简单的约束,可以在虚构的资源库中查找文章:
public class SlugRouteConstraint : IRouteConstraint { private readonly ISlugRepository slugRepository = new SlugRepository(); public bool Match(HttpContextBase httpContext,Route route,string parameterName,RouteValueDictionary values,RouteDirection routeDirection) { if (!values.ContainsKey(parameterName)) return false; var slug = (string)values[parameterName]; return slugRepository.Exists(slug); } }
你可以按照这样的方式连线:
routes.MapRoute("Slugs","{slug}",new { controller = "Articles",action = "View" },new { slug = new SlugConstraint() });