An ASP.NET MVC path that does not start with some literal

I need to create a route for a url that does not start with some literal. I created the following route definition:

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

but it looks like it is not working

+4
source share
1 answer

You can try with route restriction:

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

All Articles