当前位置: 爱符号 - 所有分类 - Web开发 - ASP.NET - asp.net 简简单单实现url重写
asp.net 简简单单实现url重写 asp.net JianJianDanDanShiXianurlZhongXie
小伟 发表于:2012-10-16 17:29:16 阅读(1444)
关键词:asp.net asp.net url重写 url重写
摘要:asp.net 简简单单实现url重写

首先写一个类,继承于IHttpModule

代码如下:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Collections.Specialized;
namespace Demo
{
    public class UrlReWrite : IHttpModule
    {
        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(application_BeginRequest);
        }
        void application_BeginRequest(object sender, EventArgs e)
        {

            HttpContext Context = ((HttpApplication)sender).Context;
            HttpRequest Request = Context.Request;
            HttpResponse Response = Context.Response;
            string RequestPath = Request.FilePath;
            if (Path.GetExtension(RequestPath).ToLower() == ".htm")
            {
                NameValueCollection NVC = Request.QueryString;
                string QueryStr = "";
                if (NVC.Count > 0)
                {
                    foreach (string key in NVC.AllKeys)
                    {
                        QueryStr += "&" + key + "=" + NVC[key];
                    }
                    QueryStr = "?" + QueryStr.TrimStart('&');
                }
                Context.RewritePath("Default.aspx" + QueryStr);
            }

        }
        public void Dispose()
        {

        }
    }
}
iis 6.0


然后在web.config中system.web中httpModules中注册该模块<add name="UrlReWrite" type="Demo.UrlReWrite,Demo"/> name可以随便写,Demo.UrlReWrite为命名空间加上这个类名,Demo为该程序集的名称

(iis7.0在system.webServer中modules节点下注册,其他的都一样)


声明:以上内容仅代表作者观点,不代表爱符号赞成此内容或立场