Exclude controller from default route C # MVC

I would like the route not to work with one of my controllers called MyController

.

I thought it 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)$" }
);

      

Unfortunately this does not allow me to switch to any of my controllers.

I can get it to not match if the controller contains MyController

using (!?MyController.*)

, but that doesn't match it exactly.

All the regex testers I've tried show that it should only match exactly MyController

.

+3


source to share


1 answer


Found here http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints

Create a NotEqual class for 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 RouteConfig

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{urlId}",
    defaults: new { controller = "Home", action = "Index", urlId = UrlParameter.Optional },
    constraints: new { controller = new NotEqual("MyController") }
);

      

+4


source







All Articles