ASP.NET MVC路由不以某些文字开头

时间:2010-12-11 08:26:36

标签: c# .net asp.net-mvc

我需要为url创建一个不从某个文字开始的路由。我创建了以下路由定义:

    routes.MapRoute("",
                    "{something}",
                    new { Controller = "Home", Action = "Index" },
                    new
                        {
                            something = "^(?!sampleliteral)"
                        });

但看起来不起作用

1 个答案:

答案 0 :(得分:4)

您可以尝试使用路线约束:

public class MyConstraint: IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var value = values[parameterName] as string;
        if (!string.IsNullOrEmpty(value))
        {
            return !value.StartsWith("sampleliteral", StringComparison.OrdinalIgnoreCase);
        }
        return true;
    }
}

然后:

routes.MapRoute(
    "",
    "{something}",
    new { Controller = "Home", Action = "Index", something = UrlParameter.Optional },
    new { something = new MyConstraint() }
);