"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Creating a Custom Route Constraint (C#)

by Stephen Walther

Stephen Walther demonstrates how you can create a custom route constraint. We implement a simple custom constraint that prevents a route from being matched when a browser request is made from a remote computer.

The goal of this tutorial is to demonstrate how you can create a custom route constraint. A custom route constraint enables you to prevent a route from being matched unless some custom condition is matched.

In this tutorial, we create a Localhost route constraint. The Localhost route constraint only matches requests made from the local computer. Remote requests from across the Internet are not matched.

You implement a custom route constraint by implementing the IRouteConstraint interface. This is an extremely simple interface which describes a single method:

[!code-csharpMain]

   1:  bool Match(
   2:      HttpContextBase httpContext,
   3:      Route route,
   4:      string parameterName,
   5:      RouteValueDictionary values,
   6:      RouteDirection routeDirection
   7:  )

The method returns a Boolean value. If you return false, the route associated with the constraint won’t match the browser request.

The Localhost constraint is contained in Listing 1.

Listing 1 - LocalhostConstraint.cs

[!code-csharpMain]

   1:  using System.Web;
   2:  using System.Web.Routing;
   3:  namespace MvcApplication1.Constraints
   4:  {
   5:      public class LocalhostConstraint : IRouteConstraint
   6:      {
   7:          public bool Match
   8:              (
   9:                  HttpContextBase httpContext, 
  10:                  Route route, 
  11:                  string parameterName, 
  12:                  RouteValueDictionary values, 
  13:                  RouteDirection routeDirection
  14:              )
  15:          {
  16:              return httpContext.Request.IsLocal;
  17:          }
  18:      }
  19:  }

The constraint in Listing 1 takes advantage of the IsLocal property exposed by the HttpRequest class. This property returns true when the IP address of the request is either 127.0.0.1 or when the IP of the request is the same as the server’s IP address.

You use a custom constraint within a route defined in the Global.asax file. The Global.asax file in Listing 2 uses the Localhost constraint to prevent anyone from requesting an Admin page unless they make the request from the local server. For example, a request for /Admin/DeleteAll will fail when made from a remote server.

Listing 2 - Global.asax

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.Mvc;
   6:  using System.Web.Routing;
   7:  using MvcApplication1.Constraints;
   8:  namespace MvcApplication1
   9:  {
  10:      public class MvcApplication : System.Web.HttpApplication
  11:      {
  12:          public static void RegisterRoutes(RouteCollection routes)
  13:          {
  14:              routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  15:              routes.MapRoute(
  16:                  "Admin",
  17:                  "Admin/{action}",
  18:                  new {controller="Admin"},
  19:                  new {isLocal=new LocalhostConstraint()}
  20:              );
  21:              //routes.MapRoute(
  22:              //    "Default",                                              // Route name
  23:              //    "{controller}/{action}/{id}",                           // URL with parameters
  24:              //    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
  25:              //);
  26:          }
  27:          protected void Application_Start()
  28:          {
  29:              RegisterRoutes(RouteTable.Routes);
  30:          }
  31:      }
  32:  }

The Localhost constraint is used in the definition of the Admin route. This route won’t be matched by a remote browser request. Realize, however, that other routes defined in Global.asax might match the same request. It is important to understand that a constraint prevents a particular route from matching a request and not all routes defined in the Global.asax file.

Notice that the Default route has been commented out from the Global.asax file in Listing 2. If you include the Default route, then the Default route would match requests for the Admin controller. In that case, remote users could still invoke actions of the Admin controller even though their requests wouldn’t match the Admin route.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-a-custom-route-constraint-cs.htm
< THANKS ME>