By implementing the IRouteConstraint interface, you can restrict a control name. This article focuses on custom constraints. For more information, see:
MVC custom route 01-why do I need custom routing?
using System.Web.Mvc;
using System.Web.Routing;
using MvcApplication2.Extension;
namespace MvcApplication2
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Effect
□Implement the IRouteConstraint Interface
using System;
using System.Web.Routing;
namespace MvcApplication2.Extension
{
public class ExcludeController : IRouteConstraint
{
private readonly string _controller;
public ExcludeController(string controller)
{
_controller = controller;
}
public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// If the controller value obtained in the route is equal to the value set by the constraint, false is returned.
return !string.Equals(values["controller"].ToString(), _controller, StringComparison.OrdinalIgnoreCase);
}
}
}
□Route adding Constraints
using System.Web.Mvc;
using System.Web.Routing;
using MvcApplication2.Extension;
namespace MvcApplication2
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { controller = new ExcludeController("RentalProperties") }
);
}
}
}
Effect
As you can see, when you add custom constraints, the controller with the RentalProperties name will be restricted.