ASP.NET——URL重写,伪静态

我们用.net开发的网站,都是动态网页。其扩展名一般是.aspx,ashx等。有的时候还带着参数,如:http://www.NLYJF.com/user/blogs.aspx?id=2123 此类样式的URL,这样的格式对用户来说,很难看,感觉很不舒服。而搜索引擎在收录链接的时候,排名也会靠后。因此我们有必要把URL写成类似于: http://www.NLYJF.com/user/blogs/2123.html 这样的形式。

在用户输入.html的时候,其实访问的是.aspx格式的网页,只不过中间被“转换”了一下。

URL重写:

①新建一个全局配置文件,Global.asax。

②在Global.asax中,在BeginRequest阶段添加代码

BeginRequest
void Application_BeginRequest(object sender,EventArgs e)
{
//Accept the URL inputed by users
string url=Request.RawUrl;

Regex regex=new Regex(@"user/blogs/(\d+).htm");

Match match=regex.Match(url);
if(match.Success)
{

string id=match.Gourp[1].Value;

string s="user/blogs.aspx?id="+id;

HttpContext.Current.RewritePath(s);
}
}

要想URL重写,肯定是会用到正则表达式的。

这样,就成功了。

——————————————————————

另外,微软还提供了一个dll文件,URLWriter.dll ,

我们也可以使用它来直接进行URL重写。

①添加引用URLwriter.dll文件

②在web.config文件中,找到<configSections>节点,在结束标志</configSections>前添加代码

第一步
<configSections>
<section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandlers, URLRewriter">

</configSections>

③在web.config文件中,还是找到<configSections>节点,在结束标志</configSections>后,添加代码

第二步
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/user/blogs.aspx</LookFor>
<SendTo>~/user/blogs.aspx?id=$1</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>

④找到节点<httpHandlers>,在<httpHandlers>中添加

<add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler,URLRewriter"/>

 

转载于:https://www.cnblogs.com/laov/archive/2012/02/08/2342985.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值