一个简单的url重写

如有不明白的地方欢迎加QQ群14670545 探讨

首先需要知道web中url请求的原理,具体的大家看这位兄弟的博客:http://www.cnblogs.com/tangself/archive/2011/03/28/1998007.html

HttpModule要有一定的认识,这里我们来做个简单的例子,将.aspx后缀的文件伪实现成.html后缀的

1.新建页面Default.aspx,写入页面代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="mystudy.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>测试一下</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ol>
            <li><a href="new/showtopic-1.html" title="UserInfo1.aspx">编号为1的用户信息</a></li>
            <li><a href="showtopic-2.html" title="UserInfo2.aspx">编号为2的用户信息</a></li>
            <li><a href="showtopic-3.html" title="UserInfo3.aspx">编号为3的用户信息</a></li>
            <li><a href="showtopic-4.html" title="UserInfo4.aspx">编号为4的用户信息</a></li>
            <li><a href="UserInfo.aspx?UserId=5" title="UserInfo5.aspx">编号为5的用户信息</a></li>
            <li><a href="fdsaf.aspx" title="fdsaf.aspx">不按规则(fdsaf.aspx)来的url请求</a></li>
        </ol>
    </div>
    </form>
</body>
</html>
2.新建类库Web.UI,在里面添加一个UrlReWriter.cs类,写入下面代码:

using System;
using System.Text.RegularExpressions;
using System.Web;

namespace Web.UI
{
    /// <summary>
    ///UrlReWriter 的摘要说明
    /// </summary>
    public class UrlReWriter : IHttpModule
    {
        public UrlReWriter()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        #region IHttpModule 成员

        public void Dispose()
        {
            //这里写Dispose代码
        }
        public void Init(HttpApplication context)
        {
            #region
            //BeginRequest	指示请求处理开始
            //AuthenticateRequest	封装请求身份验证过程
            //AuthorizeRequest	封装检查是否能利用以前缓存的输出页面处理请求的过程
            //ResolveRequestCache	从缓存中得到相应时候触发
            //AcquireRequestState	加载初始化Session时候触发
            //PreRequestHandlerExecute	在Http请求进入HttpHandler之前触发
            //PostRequestHandlerExecute	在Http请求进入HttpHandler之后触发
            //ReleaseRequestState	存储Session状态时候触发
            //UpdateRequestCache	更新缓存信息时触发
            //EndRequest	在Http请求处理完成的时候触发
            //PreSendRequestHenaders	在向客户端发送Header之前触发
            //PreSendRequestConternt	在向客户端发送内容之前触发
            #endregion

            //context.BeginRequest是开始处理HTTP管线请求时发生的事件
            context.BeginRequest += new EventHandler(context_BeginRequest);
            //context.Error是当处理过程中发生异常时产生的事件
            context.Error += new EventHandler(context_Error);
        }
        void context_Error(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            context.Response.Write("<html>");
            context.Response.Write("<head><title>出错了!</title></head>");
            context.Response.Write("<body style=\"font-size:14px;\">");
            context.Response.Write("出错了:<br />");
            context.Response.Write("<textarea name=\"errormessage\" style=\"width:80%; height:200px; word-break:break-all\">");
            context.Response.Write(HttpUtility.HtmlEncode(context.Server.GetLastError().ToString()));
            context.Response.Write("</textarea>");
            context.Response.Write("</body></html>");
            context.Response.End();
        }
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            HttpResponse response = context.Response;
            string path = context.Request.Path;
            string file = System.IO.Path.GetFileName(path);
            //重写后的URL地址
            Regex regex = new Regex("showtopic-(\\d+).html", RegexOptions.Compiled);
            Match match = regex.Match(file);
            //如果满足URL地址重写的条件
            if (match.Success)
            {
                //将其按照UserInfo.aspx?UserId=123这样的形式重写,确保能正常执行
                context.RewritePath("UserInfo.aspx?UserId=" + match.Groups[1].Value);
            }
        }
        #endregion
    }
}
然后生成一下

3.修改Web.config文件,在它的httpModules节点下新增字段:

<httpModules>
	<add type="Web.UI.UrlReWriter" name="UrlReWriter"/>
</httpModules>
注意这里的type属性和name属性的值的写法,切勿搞错了。

好了,我们的web层引用一下Web.UI,然后我们在浏览器中浏览一下Default.aspx

注意第1个和第6个都不行,因为不是按照规则来进行的


是不是OK了呢,试验一下吧

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值