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路由。

转载于:https://www.cnblogs.com/liyou-blog/archive/2009/09/27/mvc.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值