first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

ASP.NET MVC: “Tip #30 – Create Custom Route Constraints”; NotEqual Constraint ; Stephen Walther

Creating a NotEqual Constraint

The easiest way to exclude one set of pages from matching a particular route is to take advantage of the custom route constraint in Listing 2.

Listing 2 – NotEqualConstraint.cs

using System;  
using System.Web;  
using System.Web.Routing;  

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

Here’s how you can use the NotEqual constraint to exclude the /Admin pages from the Default route:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }, 
    new { controller = new NotEqual("Admin") }
);

This route won’t match any request when the controller parameter gets the value Admin. For example, this route won’t match the URLs /Admin/DeleteAll or /Admin/Index.

[http://stephenwalther.com/blog/archive/ 2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx]

mod date: 2009-09-16T01:02:38.000Z