开发者

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

开发者 https://www.devze.com 2023-01-29 20:09 出处:网络
I need to create a route for url that doesn\'t start from some literal. I have created the following route definition:

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

精彩评论

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