SiberianGuy
SiberianGuy

Reputation: 25312

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

but looks like it doesn't work

Upvotes: 4

Views: 422

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

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

Upvotes: 4

Related Questions