reating a Custom Route Constraint (C#) -2

本次教程的目标是展示如何创建一个自定义的路由。自定义路由能让你保护路由免受不必要的匹配的打搅。

在此次教程中,我们将创建一个Localhost得路由约束。这个约束仅仅匹配本地主机的请求,来自Internet的远程主机的请求将不匹配。

你可以通过实现IRouteConstraint 接口,启用一个自定义的路由约束。这是一个描述了一个Match方法的简单接口:
bool Match( 
        HttpContextBase httpContext, 
        Route route, 
        
string parameterName,
        RouteValueDictionary values, 
        RouteDirection routeDirection
这个方法返回一个Boolean值。如果你返回false,于此相关的路由将不会匹配请求。

下面是Localhost约束:

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

namespace MvcApplication1.Constraints 

    
public class LocalhostConstraint : IRouteConstraint 
    { 
        
public bool Match(
            HttpContextBase httpContext,
            Route route,
            
string parameterName, 
            RouteValueDictionary values, 
            RouteDirection routeDirection
            )
        {
            
return httpContext.Request.IsLocal; 
        } 
    }
}
这个约束利用httprequest类暴露出来的islocal属性。当请求的ip事127.0.0.1或是服务器的ip时,islocal属性返回true.

你需要在Global.asax文件里吧这个约束用到一个路由里。如下表, Global.asax使用localhost约束来防止任何人访问 Admin page,除非他的ip为本地服务器的ip.例如,一个来自远程主机的请求( /Admin/DeleteAl)会失败。
using System;
using System.Collections.Generic;
using System.Linq; using System.Web; 
using System.Web.Mvc; 
using System.Web.Routing;
using MvcApplication1.Constraints; 
namespace MvcApplication1

    
public class MvcApplication : System.Web.HttpApplication
    { 
        
public static void RegisterRoutes(RouteCollection routes) 
        { 
            routes.IgnoreRoute(
"{resource}.axd/{*pathInfo}"); 
            routes.MapRoute( 
                
"Admin"
                
"Admin/{action}"
                
new {controller="Admin"}, 
                
new {isLocal=new LocalhostConstraint()} 
                ); 

            
//routes.MapRoute( 
                
// "Default",
                
// Route name 
                
// "{controller}/{action}/{id}", 
                
// URL with parameters 
                
// new { controller = "Home", action = "Index", id = "" } 
                
// Parameter defaults 
                
//);
        } 
        
protected void Application_Start() { RegisterRoutes

(RouteTable.Routes); 
        }
    } 

localhost约束被使用到admn路由上。这个路由不会匹配远程游览器的请求。然而,事实上,在Global.asax里定义的其他路由可能会匹配这类请求。这很重要:在Global.asax里,一个约束保护一个路由,而不是保护所有的路由。

注意到, 在Global.asax里删除了默认路由,因为如果不删除,他会匹配对admin控制器的请求,这样其他主机也可以访问到admin page。即使他匹配admin路由。
posted @ 2009-09-27 23:26  liyou  阅读(370)  评论(0编辑  收藏  举报