Here's a simple constraint that looks up an article slug in a fictional repository:
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);
}
}
You could wire up the constraint like this:
routes.MapRoute("Slugs", "{slug}",
new { controller = "Articles", action = "View" },
new { slug = new SlugConstraint() });
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…