上面介绍的是最简单的一种定义方式。当然我们可以建立更复杂的规则。其中就包括设定规则的默认值以及设定规则的正则表达式。

UrlRouting高级应用

预计效果:


当我访问/a/b.aspx时就会转到Default.aspx?category=a&action=b在页面上显示
category:a
action:b 亦如果我访问/chsword/xxxx.aspx就会转到Default.aspx?category=chsword&action=xxxx就会显示
category:chsword action:xxxx
 
如果访问/chsword/就会转到 Default.aspx?category=chsword&action=index就会显示
 category:chsword action:index
 

首先我建立一个Route


routes.Add(
                "Default",
                new Route("{category}/{action}.aspx",
                          new RouteValueDictionary(
                              new
                                  {
                                      file = "Default",
                                      category = "home",
                                      action = "index"
                                  }), new MyRouteHandler()
                    )
                );

当然IHttpHandler的处理方式也要有所改变

为了方便查看我使用了下方法:


    context.Server.Execute(string.Format("/{0}.aspx?category={1}&action={2}",
              RequestContext.RouteData.Values.ContainsKey("file")
                ? RequestContext.RouteData.Values["file"].ToString()
                : "default",
              RequestContext.RouteData.Values.ContainsKey("category")
                ? RequestContext.RouteData.Values["category"].ToString()
                : "",
              RequestContext.RouteData.Values.ContainsKey("action")
                ? RequestContext.RouteData.Values["action"].ToString()
                : "")
                );

即/a/b.aspx是映射到Default.aspx?category=a&action=b

在Default.aspx中写如下代码:

 category:<%=Request.Params["category"] %><br />
   action:<%=Request.Params["action"] %>

以显示传入的参数。

如果在IIS中设置Index.aspx时就算输入/a/也会访问到/a/index.aspx,即默认的会按RouteValueDictionary中设置的值自动补全

UrlRouting使用正则表达式规则

UrlRouting在定义的时候也可以按正则的规则来进行定义。


            routes.Add(
                "zz",
                new Route("{category}/{action}.chs",
                    new RouteValueDictionary(
                        new {
                            file = "Default",
                            category = "home",
                            action = ""
                        }),
                        new RouteValueDictionary(
                        new {
                            action = "[\\d]+"
                        }),
                    new MyRouteHandler()
                    )
            );

以上代码规定了action只能是数字则访问/a/1.chs可以正常访问。

而访问/a/b.chs则会显示未找到资源。

当然这是里可以使用更高级的正则表达式。

UrlRouting的技巧

排除UrlRouting的方法:

System.Web.Routing默认提供了一个IRouteHandler-StopRoutingHandler Class,经过它处理的URL不会被做任何处理

通常使用方法如下:

routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler()));

RouteHandler工厂:

其实IRouteHandler可以实现一个RouteHandler的简单工厂。


    public class RouteHandlerFactory : IRouteHandler
    {
        string Name { get; set; }
        public RouteHandlerFactory(string name){this.Name = name;}
        #region IRouteHandler 成员
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            if (this.Name == "mypage")
                return new MyPage(requestContext);
            if(this.Name="mypage1")
                return new MyPage1(requestContext);
        }
        #endregion
    }

规定HTTP verbs,这里要使用System.Web.Routing中的HttpMethodConstraint


void Application_Start(object sender, EventArgs e) {
    RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes){
    string[] allowedMethods = { "GET", "POST" };
    HttpMethodConstraint methodConstraints = new HttpMethodConstraint(allowedMethods);
    Route reportRoute = new Route("{locale}/{year}", new ReportRouteHandler());
    reportRoute.Constraints = new RouteValueDictionary { { "httpMethod", methodConstraints } };
    routes.Add(reportRoute);
}

Demo程序代码下载:

http://files.cnblogs.com/chsword/WebApplication3.rar

System.Web.Routing入门及进阶 下篇的更多相关文章

  1. System.Web.Routing入门及进阶 上篇

    System.Web.Routing已经作为一个程序集包含在.net3.5sp1中发布了.虽然我们并没有在3.5sp1中发现Asp.net Mvc的踪迹,但是亦以感觉到它离我们不远了. System. ...

  2. ASP.net 的URL路由选择(System.Web.Routing.dll)

    System.Web.Routing是.net 3.5sp1中新增的一个dll,用它提拱的类可以很方便的实现url的映射,在asp.net WebFrom的编程中可以使客户端请求的URL变得更加的&q ...

  3. 返璞归真 asp.net mvc (2) - 路由(System.Web.Routing)

    原文:返璞归真 asp.net mvc (2) - 路由(System.Web.Routing) [索引页] [源码下载] 返璞归真 asp.net mvc (2) - 路由(System.Web.R ...

  4. 【ASP.NET】System.Web.Routing - RouteCollection Class

    Provides a collection of routes for ASP.NET routing. The RouteCollection class provides methods that ...

  5. 【ASP.NET】System.Web.Routing - PageRouteHandler Class

    用于提供一些属性和方法来定义如何将URL匹配到一个物理文件上面. public PageRouteHandler (string virtualPath, bool checkPhysicalUrlA ...

  6. 【ASP.NET】System.Web.Routing - HttpMethodConstraint Class

    你可以自己定义你的ASP.NET程序接收的get post put 或者delete请求. 使用这个约束的方式为: void Application_Start(object sender, Even ...

  7. 【ASP.NET】System.Web.Routing - StopRoutingHandler Class

    Provides a way to specify that ASP.NET routing should not handle requests for a URL pattern. ex: rou ...

  8. 【ASP.NET】System.Web.Routing - Route Class

    Provides properties and methods for defining a route and for obtaining information about the route. ...

  9. WEB编程 入门简单 进阶难

    其实不论是WEB还是其他什么编程,都是这个道理,至于为什么,我贴几段代码,大家感受下. JS 计算今天是星期几 入门级 // 计算系统当前是星期几 var str =""; var ...

随机推荐

  1. Winform设置托盘程序,托盘显示

    1.拖一个NotifyIcon,一个ContextMenuStrip控件到主窗体中 2.设置notifyIcon1,一个contextMenuStrip1(如下图) Icon为托盘图标,Text托盘显 ...

  2. DirectoryEntry_Properties属性的遍历(win2008)

    DirectoryEntry root = new DirectoryEntry(@"IIS://localhost/W3SVC"); string PInfo = "& ...

  3. ElasticSearch 2 (3) - Breaking Changes

    ElasticSearch 2.1.1 (3) - Breaking Changes Search Changes search_type = scan Deprecated GET /my_ind ...

  4. Windows server 自带的 .net版本

    1. Win2012r2 所带的版本: 2. Win2016 所带的版本 4.6 Win2019 自带的 .net版本为: 4.7 4. 然后比较 Win2008r2sp1 使用的是 .net3.5 ...

  5. Win2008r2 由ESXi 转换到 HyperV的处理过程

    1. 大部分2008r2 采取了 windows loader的方式激活 这种方式 会导致hyperV 启动失败 因为他家在了错误的bios类型 所以第一步建议 使用windows loader 卸载 ...

  6. Shell命令——文件目录

    Linux只有一个文件系统树,不同的硬件设备可以挂载在不同目录下. 文件或目录有两种表示方式:  - 绝对路径:从根目录”/”开始  - 相对路径:从工作目录开始,使用”..”指向父目录,”.”指向当 ...

  7. java通过dom读写xml文件

    java通过dom读写xml文件 要读的xml文件 <?xml version="1.0" encoding="GB2312"?><学生花名册 ...

  8. BZOJ5461 PKUWC2018Minimax(概率期望+线段树合并+动态规划)

    离散化后,容易想到设f[i][j]为i节点权值为j的概率,不妨设j权值在左子树,则有f[i][j]=f[lson][j](pi·f[rson][1~j]+(1-pi)·f[rson][j~m]). 考 ...

  9. Educational Codeforces Round 14 D. Swaps in Permutation(并查集)

    题目链接:http://codeforces.com/contest/691/problem/D 题意: 题目给出一段序列,和m条关系,你可以无限次互相交换这m条关系 ,问这条序列字典序最大可以为多少 ...

  10. MT【80】单调性求函数表达式

    提示:$f(f(f(x)-lnx)-ln(f(x)-lnx))=1+e=f(f(x)-lnx),\because f(x)$单调.得: $f(f(x)-lnx)-ln(f(x)-lnx)=f(x)-l ...