博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Asp.net 2.0 自定义伪静态源码
阅读量:5119 次
发布时间:2019-06-13

本文共 8001 字,大约阅读时间需要 26 分钟。

根据微软官方伪静态UrlRewrite.dll源码,自己改写应用进项目中。

1、首先,我们写个用于HttpModule请求的类 RolesProvider

using System;using System.Text;using System.Web;using System.Web.Security;using System.Security.Principal;public class RolesProvider : IHttpModule{        //页面初始化        public void Init(HttpApplication context)        {            context.AuthorizeRequest += new EventHandler(this.BaseModuleRewriter_AuthorizeRequest);            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);            //context.BeginRequest += new EventHandler(context_BeginRequest);            context.Error += new EventHandler(context_Error);        }                        ///         /// 伪静态处理        ///         ///         ///         protected virtual void BaseModuleRewriter_AuthorizeRequest(object sender, EventArgs e)        {            HttpContext context = ((HttpApplication)sender).Context;            string host = context.Request.ServerVariables["HTTP_HOST"].ToLower(); //获取当前主机头            string requestPath = context.Request.Path.ToLower();      //当前请求路径 不带域名             /**这边也可以做301处理功能**/                        context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");                UtilsUrlRewrite.UrlRewrite(RewriterConfiguration.GetConfig("ConfigUrlRewrite", "ConfigUrlRewrite.config"), requestPath, context); //伪静态核心代码 详见下UtilsUrlRewrite.cs            context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");        }                ///         /// 建立用户标识时        ///         void context_AuthenticateRequest(object sender, EventArgs e)        {        }                ///         /// 请求出错时        ///         ///         ///         void context_Error(object sender, EventArgs e)        {            /*CmsSafe.UrlError();*/        }        public void Dispose()        {        }}

2、UtilsUrlRewrite.cs 伪静态处理核心代码

/**由于是参考官网例子,伪静态规则语法不变。以下代码可直接复制,设置下伪静态文件地址就可以。**/using System;using System.Web;using System.Web.Caching;using System.Collections;using System.Collections.Generic;using System.Text;using System.Configuration;using System.Xml;using System.Xml.Serialization;using System.Text.RegularExpressions;public class UtilsUrlRewrite{        public static void UrlRewrite(RewriterRuleCollection rules, string requestPath, HttpContext context)        {            for (int i = 0; i < rules.Count; i++)            {                string lookFor = "^" + UtilsUrlRewrite.ResolveUrl(context.Request.ApplicationPath, rules[i].LookFor) + "$";                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);                if (re.IsMatch(requestPath))                {                    string sendToUrl = UtilsUrlRewrite.ResolveUrl(context.Request.ApplicationPath, re.Replace(requestPath, rules[i].SendTo));                                       context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);                    UtilsUrlRewrite.RewriteUrl(context, sendToUrl);                    break;                }            }        }        internal static void RewriteUrl(HttpContext context, string sendToUrl)        {            // see if we need to add any extra querystring information            if (context.Request.QueryString.Count > 0)            {                if (sendToUrl.IndexOf('?') != -1)                    sendToUrl += "&" + context.Request.QueryString.ToString();                else                    sendToUrl += "?" + context.Request.QueryString.ToString();            }            string queryString = String.Empty;            string sendToUrlLessQString = sendToUrl;            if (sendToUrl.IndexOf('?') > 0)            {                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));                queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);            }            context.RewritePath(sendToUrlLessQString, String.Empty, queryString);        }        internal static string ResolveUrl(string appPath, string url)        {            if (url.Length == 0 || url[0] != '~')                return url;            else            {                if (url.Length == 1)                    return appPath;                if (url[1] == '/' || url[1] == '\\')                {                    if (appPath.Length > 1)                        return appPath + "/" + url.Substring(2);                    else                        return "/" + url.Substring(2);                }                else                {                    if (appPath.Length > 1)                        return appPath + "/" + url.Substring(1);                    else                        return appPath + url.Substring(1);                }            }        }    }    [Serializable()]    [XmlRoot("RewriterConfig")]    public class RewriterConfiguration    {        public static RewriterRuleCollection GetConfig(string cache, string filename)        {            if (HttpContext.Current.Cache[cache] == null)            {                RewriterRuleCollection rc = new RewriterRuleCollection();                RewriterRule r;                string filePath = UtilsString.MapPath("~/App_Data/" + filename); //伪静态文件地址                XmlDocument xd = new XmlDocument();                xd.Load(filePath);                XmlNodeList items = xd.DocumentElement.ChildNodes;                foreach (XmlNode item in items)                {                    if (item.HasChildNodes == true)                    {                        r = new RewriterRule();                        r.LookFor = item["LookFor"].InnerText;                        r.SendTo = item["SendTo"].InnerText;                        rc.Add(r);                    }                }                UtilsCache.AddCache(cache, rc, UtilsCache.GetCacheDependency(filePath));                return rc;            }            return (RewriterRuleCollection)HttpContext.Current.Cache[cache];        }    }    [Serializable()]    public class RewriterRule    {        private string lookFor, sendTo;        public string LookFor        {            get            {                return lookFor;            }            set            {                lookFor = value;            }        }        public string SendTo        {            get            {                return sendTo;            }            set            {                sendTo = value;            }        }    }    [Serializable()]    public class RewriterRuleCollection : CollectionBase    {        ///         /// Adds a new RewriterRule to the collection.        ///         /// A RewriterRule instance.        public virtual void Add(RewriterRule r)        {            this.InnerList.Add(r);        }        ///         /// Gets or sets a RewriterRule at a specified ordinal index.        ///         public RewriterRule this[int index]        {            get            {                return (RewriterRule)this.InnerList[index];            }            set            {                this.InnerList[index] = value;            }        }    }}

 3、伪静态规则文件 ConfigUrlRewrite.config ,只列出有代表性的规则

~/404.(html|aspx)
~/default.aspx?s=404
~/([\w]+)-list([0-9]+).(html|aspx)
~/default.aspx?s=$1&menuid=$2
~/([\w]+)-id([0-9]+).(html|aspx)
~/default.aspx?s=$1&id=$2

 4、在网站根目录web.config中注册HttpModule

到这就可以实现自定义伪静态功能了,跟官方UrlRewrite.dll没什么区别,就是少引用dll文件,还有可以把规则写在自己的xml或config文件中,好用xml类去操作管理。IIS6应用没有问题,IIS7+版本HttpModule 暂未学习配置。

第一学堂( )  专注于提供网站建设 (Web) 技术文摘,编程开发 PS,页面布局 HTML/CSS/JS,网站发布 IIS,网站推广 SEO,JS特效,网页素材等下载,欢迎大家投稿分享交流,一起打造最优秀的web建站学习交流平台. 更多技术学习交流QQ群:8197815

转载于:https://www.cnblogs.com/btnan/p/3929847.html

你可能感兴趣的文章
#Leetcode# 209. Minimum Size Subarray Sum
查看>>
SDN第四次作业
查看>>
DM8168 DVRRDK软件框架研究
查看>>
django迁移数据库错误
查看>>
yii 跳转页面
查看>>
洛谷 1449——后缀表达式(线性数据结构)
查看>>
Data truncation: Out of range value for column 'Quality' at row 1
查看>>
Dirichlet分布深入理解
查看>>
字符串处理
查看>>
HtmlUnitDriver 网页内容动态抓取
查看>>
ad logon hour
查看>>
获得进程可执行文件的路径: GetModuleFileNameEx, GetProcessImageFileName, QueryFullProcessImageName...
查看>>
证件照(1寸2寸)拍摄处理知识汇总
查看>>
罗马数字与阿拉伯数字转换
查看>>
Eclipse 反编译之 JadClipse
查看>>
Python入门-函数
查看>>
[HDU5727]Necklace(二分图最大匹配,枚举)
查看>>
距离公式汇总以及Python实现
查看>>
一道不知道哪里来的容斥题
查看>>
Blender Python UV 学习
查看>>