开发者

ASP.NET MVC route that doesn't start with some literal

I need to create a route for url that doesn't start from some literal. I have created the following route definition:

    routes.MapRoute("",
                    "{something}",
                    new { Controller = "Home", Action = "Index" },
                    new
                        {
                            something = "^(?!sampleliteral)"
                        });
开发者_JS百科

but looks like it doesn't work


You may try with a route constraint:

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;
    }
}

And then:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜