电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

支持正则表达式的UrlMapping


发布日期:2021/4/20
 

猛然发现ASPNET 本身就提供了对UrlMapping的天然支持——nfig文件中的<urlMappings>节感歎现在写程序真的不是什么技术活了

<?xml version=?>

<configuration>

<systemweb>

<urlMappings>

<add url=~// mappedUrl=~/Monthaspx?year=&amp;month=/>

<add url=~// mappedUrl=~/Monthaspx?year=&amp;month=/>

</urlMappings>

<compilation debug=true/>

</systemweb>

</configuration>

这个配置可以使ASPNET程序在ASPNET Development Server(就是建ASPNET项目时选文件系统)直接支持UrlMapping不过它有几个不足之处

只能映射固定的地址所以只能一个地址一个地址的配置

ASPNET Development Server中可以不用配什么别的地方在IIS中受请求响应模型所限估计还是要在IIS中设映射这样的话反而搞得我到处找资料看怎么实现在ASPNET Development Server设置映射得到的结果是不行

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

nfig中的配置举例如下

<?xml version=?>

<configuration>

<configSections>

<section name=RegexUrlMappings type=CnblogsDTCTHINRegexUrlMapping

RegexUrlMappingsSectionCnblogsDTCTHINRegexUrlMapping/>

</configSections>

<RegexUrlMappings enabled=true rebaseClientPath=true>

<add url=(\d+)$ mappedUrl=defaultaspx?id=$/>

<add url=(?&lt;=/)(?&lt;id&gt;[az]+)$ mappedUrl=defaultaspx?

id=${id} />

<add url=/$ mappedUrl=/defaultaspx?id=/>

</RegexUrlMappings>

<systemweb>

<httpModules>

<add name=RegexUrlMappingModule type=CnblogsDTCTHIN

RegexUrlMappingRegexUrlMappingModuleCnblogsDTCTHIN

RegexUrlMapping/>

</httpModules>

<compilation debug=true/>

<authentication mode=Windows/>

</systemweb>

</configuration>

其中RegexUrlMapping的属性enabled用于打开和关闭映射rebaseClientPath参见HttpContextRewritePath中rebaseClientPath参数

<add>用于添加映射规则url为匹配路径的正则表达式patternmappedUrl是替换规则用法参见RegexReplace方法

上例中第一个add在url中用括号定义了组所以在后面引用$

第二个add在url中用(?<id>)定义了组id后面用${id}引用了这个组

第三个是固定字符串替换

呵呵看来正则表达式还是很重要滴~~

上一篇:正则表达式编程Regex类用法

下一篇:init