zoukankan      html  css  js  c++  java
  • ASP.NET的URL无后缀伪静态访问,DZ论坛伪静态实现原理

    HttpModule类:

    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;
    
    using System.Xml;
    using System.Text.RegularExpressions;
    using System.IO;
    
    
    /// <summary>
    /// HttpModule 的摘要说明
    /// </summary>
    public class HttpModule : System.Web.IHttpModule
    {
        /// <summary>
        /// 实现接口的Init方法
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            //可在此添加复位用户在线表
            context.BeginRequest += new EventHandler(ReUrl_BeginRequest);
        }
        /// <summary>
        /// 发生错误时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Application_OnError(Object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            context.Response.Write("<html><body style=\"font-size:14px;\">");
            context.Response.Write("Discuz!NT Error:<br />");
            context.Response.Write("<textarea name=\"errormessage\" style=\"80%; height:200px; word-break:break-all\">");
            context.Response.Write(System.Web.HttpUtility.HtmlEncode(context.Server.GetLastError().ToString()));
            context.Response.Write("</textarea>");
            context.Response.Write("</body></html>");
            context.Response.End();
        }
        /// <summary>
        /// 实现接口的Dispose方法
        /// </summary>
        public void Dispose()
        {
        }
        /// <summary>
        /// 重写Url
        /// </summary>
        /// <param name="sender">事件的源</param>
        /// <param name="e">包含事件数据的 EventArgs</param>
        private void ReUrl_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            //站内路径
            string rewriterPath = ConfigurationSettings.AppSettings["ForumPath"].ToString();
            //请求的路径
            string requestPath = context.Request.RawUrl.ToLower();
            string tmUrl = string.Empty,tmUrlPath=string.Empty;
            foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
            {
                //请求路径,路径规则形式,不区分大小写
                if (Regex.IsMatch(requestPath, url.Pattern.Replace("^","\\&"), RegexOptions.Compiled | RegexOptions.None | RegexOptions.IgnoreCase))
                {
                    string newUrl = Regex.Replace(requestPath, url.Pattern.Replace("^", "\\&"), url.Page, RegexOptions.Compiled | RegexOptions.None | RegexOptions.IgnoreCase);
                    context.RewritePath(newUrl,true);
                }
            }
        }
    }
    //////////////////////////////////////////////////////////////////////
    /// <summary>
    /// 站点伪Url信息类
    /// </summary>
    public class SiteUrls
    {
        #region 内部属性和方法
        private static object lockHelper = new object();
        private static volatile SiteUrls instance = null;
    
        string SiteUrlsFile = HttpContext.Current.Server.MapPath("/config/urls.config");
        private System.Collections.ArrayList _Urls;
        public System.Collections.ArrayList Urls
        {
            get
            {
                return _Urls;
            }
            set
            {
                _Urls = value;
            }
        }
    
        private System.Collections.Specialized.NameValueCollection _Paths;
        public System.Collections.Specialized.NameValueCollection Paths
        {
            get
            {
                return _Paths;
            }
            set
            {
                _Paths = value;
            }
        }
    
        private SiteUrls()
        {
            Urls = new System.Collections.ArrayList();
            Paths = new System.Collections.Specialized.NameValueCollection();
    
            XmlDocument xml = new XmlDocument();
    
            xml.Load(SiteUrlsFile);
    
            XmlNode root = xml.SelectSingleNode("urls");
            //取得url地址
            foreach (XmlNode n in root.ChildNodes)
            {
                //重写属性xml
                if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "rewrite")
                {
                    //名称属性
                    XmlAttribute name = n.Attributes["name"];
                    //路径
                    XmlAttribute path = n.Attributes["path"];
                    //指向地址
                    XmlAttribute page = n.Attributes["page"];
                    //规则形式
                    XmlAttribute pattern = n.Attributes["pattern"];
    
                    if (name != null && path != null && page != null && pattern != null)
                    {
                        Paths.Add(name.Value, path.Value);
                        Urls.Add(new URLRewrite(name.Value, pattern.Value, page.Value.Replace("^", "&")));
                    }
                }
            }
        }
        #endregion
    
        public static SiteUrls GetSiteUrls()
        {
            if (instance == null)
            {
                lock (lockHelper)
                {
                    if (instance == null)
                    {
                        instance = new SiteUrls();
                    }
                }
            }
            return instance;
    
        }
    
        public static void SetInstance(SiteUrls anInstance)
        {
            if (anInstance != null)
                instance = anInstance;
        }
    
        public static void SetInstance()
        {
            SetInstance(new SiteUrls());
        }
    
    
        /// <summary>
        /// 重写伪地址
        /// </summary>
        public class URLRewrite
        {
            #region 成员变量
            private string _Name;
            public string Name
            {
                get
                {
                    return _Name;
                }
                set
                {
                    _Name = value;
                }
            }
    
            private string _Pattern;
            public string Pattern
            {
                get
                {
                    return _Pattern;
                }
                set
                {
                    _Pattern = value;
                }
            }
    
            private string _Page;
            public string Page
            {
                get
                {
                    return _Page;
                }
                set
                {
                    _Page = value;
                }
            }
            #endregion
            #region 构造函数
            public URLRewrite(string name, string pattern, string page)
            {
                _Name = name;
                _Pattern = pattern;
                _Page = page;
            }
            #endregion
        }
    
    }
    

     web.config需要修改的地方
    <appSettings><add key="ForumPath" value="/"/></appSettings>中间加红字部分
    <httpModules>下面加<add type="HttpModule" name="HttpModule"/>

    <?xml version="1.0"?>
    <!--
        注意: 除了手动编辑此文件以外,您还可以使用 Web 管理工具来
        配置应用程序的设置。
        可以使用 Visual Studio 中的“网站”->“Asp.Net 配置”选项。
        设置和注释的完整列表在    machine.config.comments 中,
       该文件通常位于
        \Windows\Microsoft.Net\Framework\v2.x\Config 中
    -->
    <configuration>
            <configSections>
                    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                                    <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                                    <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                                            <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                                            <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                                            <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                                            <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/></sectionGroup></sectionGroup></sectionGroup></configSections>
      
      <appSettings><add key="ForumPath" value="/"/></appSettings>
      <connectionStrings>
        <clear/>
        <add name="SQLConn" connectionString="server=.; database=Blog; uid=sa; pwd=2005"/>
      </connectionStrings>
            <system.web>
                    <!--
                设置 compilation debug="true" 可将调试符号
                插入已编译的页面中。
                但由于这会影响性能,因此只在开发过程中将此值
                设置为 true。
            -->
                    <compilation debug="false">
                            <assemblies>
                                    <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                                    <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                                    <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                                    <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
                    <!--
                通过 <authentication> 节可以配置 ASP.NET 用来 
                识别进入用户的
                安全身份验证模式。 
            -->
                    <authentication mode="Windows"/>
                    <!--
                如果在执行请求的过程中出现未处理的错误,
                则通过 <customErrors> 节可以配置相应的处理步骤。
                具体说来,
                开发人员通过该节可以配置
                要显示的 HTML 错误页以代替错误堆栈跟踪。
    
            <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
                <error statusCode="403" redirect="NoAccess.htm" />
                <error statusCode="404" redirect="FileNotFound.htm" />
            </customErrors>
            -->
                    <pages>
                            <controls>
                                    <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                                    <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></controls></pages>
                    <httpHandlers>
                            <remove verb="*" path="*.asmx"/>
                            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                            <add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpHandlers>
                    <httpModules>
          <add type="HttpModule" name="HttpModule"/>
                            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpModules></system.web>
            <system.codedom>
                            <compilers>
                                    <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
                                            <providerOption name="CompilerVersion" value="v3.5"/>
                                            <providerOption name="WarnAsError" value="false"/></compiler>
                                    <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
                                            <providerOption name="CompilerVersion" value="v3.5"/>
                                            <providerOption name="OptionInfer" value="true"/>
                                            <providerOption name="WarnAsError" value="false"/></compiler></compilers></system.codedom>
            <system.webServer>
                            <validation validateIntegratedModeConfiguration="false"/>
                    <modules>
                            <remove name="ScriptModule"/>
                            <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></modules>
                    <handlers>
                            <remove name="WebServiceHandlerFactory-Integrated"/>
                            <remove name="ScriptHandlerFactory"/>
                            <remove name="ScriptHandlerFactoryAppServices"/>
                            <remove name="ScriptResource"/>
                            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                            <add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></handlers></system.webServer>
            <runtime>
                    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
                            <dependentAssembly>
                                    <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
                                    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly>
                            <dependentAssembly>
                                    <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
                                    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly></assemblyBinding></runtime></configuration>
    url.config:
    
    <?xml version="1.0" encoding="utf-8" ?> 
    <urls>
      <rewrite name="showforum"
           path="/showforum/"
           pattern = "/showforum/"
           page="/showforum.aspx"/>
        <rewrite name="showtopic"
              path="showtopic/?topicid={0}^page={1}"
              pattern = "/showtopic/\?topicid=(\d+)?^page=(\d+)?"
              page="/test/showtopic.aspx?topicid=$1^page=$2" />
        <rewrite name="userinfo"
              path="/userinfo?userid={0}"
              pattern = "/userinfo\?userid=(\d+)?"
              page="/userinfo.aspx?userid=$1" />
         <rewrite name="rss"
              path="/rss/{0}"
              pattern = "/rss/(\d+)?"
              page="/rss.aspx?forumid=$1" />
    </urls>

    访问的样式:

    1.  www.XXX.com/XXX/
    2.www.XXX.com/XXX/?topicid=1^page=1
    3.www.XXX.com/XXX?topicid=1^page=1
    4.www.XXX.com/XXX

  • 相关阅读:
    PHP与WCF第一次亲密接触
    PHP操作MongoDB
    如何用SVN进行个人版本管理
    【Android】还原“微信”apk中的“发现”和“我”两个模块
    使php支持mbstring库
    mysql 与 mysqli的区别
    nginx 配置正向 HTTP 代理服务器[转]
    正向代理与反向代理的区别【Nginx读书笔记】
    为什么要使用Nginx?
    【转】关于HTTP中文翻译的讨论
  • 原文地址:https://www.cnblogs.com/flianzhu/p/2544021.html
Copyright © 2011-2022 走看看