首页 > 编程 > .NET > 正文

ASP.net的URL重写

2024-07-10 13:06:15
字体:
来源:转载
供稿:网友

asp.net的rul重写


有关于url的重写,本文也只是拿来主意。相继有ms的组件“urlrewriter”和在global.asax里的“application_beginrequest()”编码方式,以及iis里的isapi设置。

娜列下来,实现方法也都很简单。

 

方法一:ms组件

这里也不用详解了,相关请看:

http://www.microsoft.com/china/msdn/library/webservices/asp.net/urlrewriting.mspx

用法很简单,只需要把组件urlrewriter.dll拷到应用程序的bin目录下,然后在web.config下加入如下代码:

在<configuration></configuration>中加入:

<configsections>

<section name="rewriterconfig" type="urlrewriter.config.rewriterconfigserializersectionhandler, urlrewriter" />

</configsections>

 

<rewriterconfig>

<rules>

<rewriterrule>

<lookfor>~/(/d{4})/(/d{2})/default/.aspx</lookfor>

<sendto>~/default.aspx?id=$1</sendto>

</rewriterrule>

</rules>

</rewriterconfig>

然后在<system.web></system.web>中加入:

<httphandlers>

<add verb="*" path="*.aspx"

type="urlrewriter.rewriterfactoryhandler, urlrewriter" />

</httphandlers>

 

最后在地址栏上键入:http://localhost/test/2004/12/news.aspx

效果出来了。

上面的<lookfor>~/(/d{4})/(/d{2})/news/.aspx</lookfor>这句这正则表达式url,即被重写的url,而<sendto>~/default.aspx?id=$1</sendto>这一句为原始url地址。其中的$1为第一个正则表达式值(上面例子为:2004),以此类推,第二个即为$2

 

方法二:application_beginrequest()

在应用程序中新建一个xml文件,文件内容为:文件名rewriter.config

<?xml version="1.0" encoding="utf-8" ?>

<rewriterurls>

<rule>

<old>(.*)/news/(/d{4})/default/.aspx</old>

<new>../../default.aspx?id=$2&amp;type=$3</new>

</rule>

</rewriterurls>

在global.asax文件中的application_beginrequest(object sender, eventargs e)加入代码:

try

{

string path=server.mappath("~/rewriter.config");

xpathdo***ent myxpathdo***ent = new xpathdo***ent(path);

xpathnavigator myxpathnavigator = myxpathdo***ent.createnavigator();

xpathnodeiterator myxpathnodeiterator = myxpathnavigator.select ("//rule");

system.text.regularexpressions.regex oreg;

string rewriteurl;

while (myxpathnodeiterator.movenext())

{

//oreg=new regex(onode.selectsinglenode("url/text()").value);

xpathnavigator nav2 = myxpathnodeiterator.current.clone();

string oldstring="",newstring="";

xpathnodeiterator it2 = nav2.select("old");

while(it2.movenext())

{

oldstring = it2.current.value;

break

}

it2 = nav2.select("new");

while(it2.movenext())

{

newstring = it2.current.value;

break

}

if(oldstring != "" && newstring != "")

{

oreg = new system.text.regularexpressions.regex(oldstring);

if(oreg.ismatch(request.url.tostring()))

{

rewriteurl = oreg.replace(request.url.tostring(),newstring);

httpcontext.current.rewritepath(rewriteurl);

break

}

}

}

}

catch

{

}

注册会员,创建你的web开发资料库,
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表