首页 > 编程 > .NET > 正文

ASP.NET实现伪静态网页方法小结

2024-07-10 12:48:25
字体:
来源:转载
供稿:网友

本文实例总结了ASP.NET实现伪静态网页方法,之用。具体方法如下:

方法一:利用Httphandler实现URL重写(伪URL及伪静态)

我们有时候会见到这样的地址:“http://www.XXXX.com/show-12-34.html”,你或许认为在站点服务器根目录“/”下存在名为“show-12-34.html”的文件,其实实际它可能是不存在的,而可能你看到的内容是“/aspx/show.aspx?type= 12&id=34”的内容,为什么要这样做呢?原因有多个方面:首先是增强URL的友好性,记“show-12-34.html”总比 “/aspx/show.aspx?type=12&id=34”好记吧?其次就是方便搜索引擎收录,很多搜索引擎更看好静态HTML页,比如:百度;其次就是出于安全性的考虑,因为这样隐藏了参数“type”、“id”。是不是很有意思呢?

其实这是利用URL重写实现的,下面我就说一下在ASP.NET2.0下我所知道的最简单的实现方法:通过实现接口“IHttpHandler”来接管HTTP请求,Follow me!

1.在资源管理方案中添加一个类,类的代码如下:

//类URLRewriter程序清单: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; /// <summary> /// UrlRewriter URL重写类  /// Author:yoyo /// </summary> public class UrlRewriter : IHttpHandler //实现“IHttpHandler”接口 {  public UrlRewriter() { // // TODO: 在此处添加构造函数逻辑  // } public void ProcessRequest(HttpContext Context) { try { //取得原始URL屏蔽掉参数 string Url = Context.Request.RawUrl; //建立正则表达式   System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex   (@"/show-(/d+)-(/d+)/..+",System.Text.RegularExpressions.RegexOptions.IgnoreCase); //用正则表达式进行匹配 System.Text.RegularExpressions.Match m = Reg.Match(Url,Url.LastIndexOf("/"));//从最后一个“/”开始匹配 if (m.Success)//匹配成功 { String RealPath = @"~/aspx/show.aspx?type=" + m.Groups[1] + "&id=" + m.Groups[2]; //Context.Response.Write(RealPath); //Context.RewritePath(RealPath);//(RewritePath 用在无 Cookie 会话状态中。) Context.Server.Execute(RealPath); } else  { Context.Response.Redirect(Context.Request.Url.ToString()); } } catch { Context.Response.Redirect(Context.Request.Url.ToString()); } } /// <summary> /// 实现“IHttpHandler”接口所必须的成员 /// </summary> /// <value></value> /// Author:yoyo public bool IsReusable { get { return false; } }}

2.在web.config文件还要添加以下设置项

在<system.web>节点下添加如下代码:

<httpHandlers> 
<add verb="*" path="*/show-?*-?*.aspx" type="UrlRewriter" /> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表