当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net URL重写简化版 速学URL重写

asp.net URL重写简化版 速学URL重写

2017年12月12日  | 移动技术网IT编程  | 我要评论

感觉不到你对我说谎,乘胜追击粤语在线观看,碧昂斯经典歌曲

在 asp.net 里实现 url重写(urlrewriter)的一个最简单的方法。
参考了 (作者 scott mitchell 翻译:janssen )的大作,虽然没有完全看明白,但是也照猫画虎地做了一个,颇有“成就”感。写出来分享一下。
原作里讲了很多的原理,这里就不说了(其实我也不懂)。这里就写操作过程吧。目的是实现一个最简单的能实现 url重写 的程序。
1、需要设置一下iis里的站点属性。

2、修改web.config的内容。

复制代码 代码如下:

<system.web>
<httphandlers>
<add verb="*" path="*.zhtml" type="zdil.urlrewriter.rewriterfactoryhandler, zdilurlrewriter" />
</httphandlers>
</system.web>


其中*.zhtml 就是地址栏里面写的网页的扩展名,就是给用户看的,这个可以随意改(但是要符合扩展名的规则!)。当然要和第一步里面的设置相一致才行。
3、写一个类。

代码
复制代码 代码如下:

using system;
using system.io;
using system.web;
using system.web.ui;
namespace zdil.urlrewriter
{
/**//// <summary>
/// url重写
/// </summary>
public class rewriterfactoryhandler : ihttphandlerfactory
{
/**//// <summary>
/// gethandler is executed by the asp.net pipeline after the associated httpmodules have run. the job of
/// gethandler is to return an instance of an httphandler that can process the page.
/// </summary>
/// <param name="context">the httpcontext for this request.</param>
/// <param name="requesttype">the http data transfer method (<b>get</b> or <b>post</b>)</param>
/// <param name="url">the rawurl of the requested resource.</param>
/// <param name="pathtranslated">the physical path to the requested resource.</param>
/// <returns>an instance that implements ihttphandler; specifically, an httphandler instance returned
/// by the <b>pageparser</b> class, which is the same class that the default asp.net pagehandlerfactory delegates
/// to.</returns>
public virtual ihttphandler gethandler(httpcontext context, string requesttype, string url, string pathtranslated)
{
string sendtourl = url; //地址栏里面的地址
string filepath = pathtranslated;
string sendtourlstring = "/web/index.aspx"; //真正要访问的页面
string querystring = ""; //参数。比如 ?id=123
filepath = context.server.mappath(sendtourlstring); //物理地址
//这句最重要了。转向了。
context.rewritepath(sendtourlstring, string.empty, querystring);
return pageparser.getcompiledpageinstance(url, filepath, context);
}
public virtual void releasehandler(ihttphandler handler)
{
}
}
}


这个类呢,要写在一个单独的项目里面,然后编译成 zdilurlrewriter.dll文件。(注意文件名,写错了就不能正常运行了)。
4、完成了。
打开ie ,在地址栏里输入 http://.../1.zhtml。
浏览者看到是一个静态页的地址,但是实际上访问的却是 /web/index.aspx 这个动态网页。
怎么样简单吧。
当然了,这个是最简单的,简单到了“不能用”的地步了。因为他会把所有的 *.zhtml 的访问都“重写”到 /web/index.aspx 。
至于把什么样的网页重写到哪个网页,这里就不介绍了(这里只讲方法,不讲实现的细节)。
方法很多了,原作是通过正则来匹配的,我是通过 string sendtourl = url; 来判断的。
其他的就看你们的需要了。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网