Reputation: 23690
I'd like to prevent a route from handling one of my controllers, called MyController
.
I thought this might work, but it doesn't:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{urlId}",
defaults: new { controller = "Home", action = "Index", urlId = UrlParameter.Optional },
constraints: new { controller = @"^(!?MyController)$" }
);
Sadly it stops me from navigating to any of my controllers.
I can only get it not to match if the controller contains MyController
using (!?MyController.*)
but this isn't matching it exactly.
All of the regex testers I've tried suggest that it should only match exactly MyController
.
Upvotes: 4
Views: 4092
Reputation: 1931
Found this here http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints
Create the NotEqual class to use in your constraints
public class NotEqual : IRouteConstraint
{
private string _match = String.Empty;
public NotEqual(string match)
{
_match = match;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return String.Compare(values[parameterName].ToString(), _match, true) != 0;
}
}
Then use the class in your RouteConfig
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{urlId}",
defaults: new { controller = "Home", action = "Index", urlId = UrlParameter.Optional },
constraints: new { controller = new NotEqual("MyController") }
);
Upvotes: 10