BluRayCD Forum

 找回密码
 立即注册【分享大片】
查看: 380|回复: 0
收起左侧

[交流分享] web.config中的urlMappings使用方法和实例

[复制链接]

410

主题

177

回帖

1万

积分

Forum CEO

金币
2568 枚
体力
11797 点
kmxmxy 发表于 2011-4-21 16:06:29 | 显示全部楼层 |阅读模式
自己建个web.config文件,粘入下面的代码

程序代码
  1. <system.web>
  2.   <urlMappings enabled="true">
  3.      <add url="~/login.html" mappedUrl="default.aspx?state=222"/>
  4.      <add url="~/login.aspx" mappedUrl="default.aspx?state=6"/>
  5.   </urlMappings>
  6. </system.web>
复制代码
下面转载一篇相关介绍:

猛然发现ASP.NET 2.0本身就提供了对UrlMapping的天然支持--web.config文件中的<urlMappings>节,感叹现在写程序真的不是什么技术活了。

程序代码
  1. <?xml version="1.0"?>
  2. <configuration>
  3.     <system.web>
  4.         <urlMappings>
  5.             <add url="~/2006/07" mappedUrl="~/Month.aspx?year=2006&month=01"/>
  6.             <add url="~/2006/08" mappedUrl="~/Month.aspx?year=2006&month=02"/>

  7.         </urlMappings>
  8.         <compilation debug="true"/>
  9.   </system.web>
  10. </configuration>
复制代码
这个配置可以使ASP.NET程序在ASP.NET Development Server(就是建ASP.NET项目时选文件系统)直接支持UrlMapping,不过它有几个不足之处:
1、只能映射固定的地址,所以只能一个地址一个地址的配置
2、 ASP.NET Development Server中可以不用配什么别的地方,在IIS中受请求响应模型所限,估计还是要在IIS中设映射。这样的话,反而搞得我到处找资料,看怎么实现在 ASP.NET Development Server设置映射,得到的结果是不行。

针对于UrlMapping的不支持正则表达式的缺陷,我做了个支持正则表达式的UrlMapping,可惜由于UrlMapping是由HttpApplication调用的,而 HttpApplication是Internal的,不能对它做什么动作,所以实现的东东和UrlMapping相比做在Web.config中多做个<Section>

文件下载

(下载文件中包括RegexUrlMapping组件和一个示例ASP.NET,注意ASP.NET程序需部署在IIS中,并且要设置映射,方法是右击虚拟目录,选属性,选配置,在通配符应用程序映射中添加c:\windows\microsoft.net\framework\v2.0.50727 \aspnet_isapi.dll的引用,并去掉确认文件是否存在的钩,这里是为了偷懒才用通配符全部映射到ASP.NET2.0的ISAPI,实际开发中最好酌情添加具体一点的映射)

Web.config中的配置举例如下:
  1. <?xml version="1.0"?>
  2. <configuration>
  3.     <configSections>
  4.         <section name="RegexUrlMappings" type="Cnblogs.DTC.THIN.RegexUrlMapping.RegexUrlMappingsSection,Cnblogs.DTC.THIN.RegexUrlMapping"/>
  5.     </configSections>
  6.     <RegexUrlMappings enabled="true" rebaseClientPath="true">
  7.         <add url="(\d+)$" mappedUrl="default.aspx?id=$1"/>
  8.         <add url="(?<=/)(?<id>[a-z]+)$" mappedUrl="default.aspx?id=${id}" />
  9.         <add url="/$" mappedUrl="/default.aspx?id=0"/>
  10.     </RegexUrlMappings>
  11.     <system.web>
  12.         <httpModules>
  13.             <add name="RegexUrlMappingModule" type="Cnblogs.DTC.THIN.RegexUrlMapping.RegexUrlMappingModule,Cnblogs.DTC.THIN.RegexUrlMapping"/>
  14.         </httpModules>
  15.         <compilation debug="true"/>
  16.         <authentication mode="Windows"/>
  17.     </system.web>
  18. </configuration>
复制代码
其中RegexUrlMapping的属性enabled用于打开和关闭映射,rebaseClientPath参见HttpContext.RewritePath中rebaseClientPath参数
<add>用于添加映射规则,url为匹配路径的正则表达式pattern,mappedUrl是替换规则,用法参见Regex.Replace方法
上例中,第一个add在url中用括号定义了组1,所以在后面引用$1
第二个add在url中用(?<id>)定义了组id,后面用${id}引用了这个组
第三个是固定字符串替换
您知道吗,申请VIP会员可以免回复下载,无广告骚扰, 点此处申请

本版积分规则

小黑屋|手机版|Archiver|4K蓝光论坛

GMT+8, 2024-4-29 05:01

Copyright © 2001-2021, Gadaddy Cloud.

快速回复 返回顶部 返回列表