利用UrlRewrite,asp.net動態產生htm頁面【收藏】

來源:互聯網
上載者:User
 前段時間做項目,一直都在尋找一種動態產生htm頁面的方法,要求配置簡單,和項目無關。
  功夫不負有心人,終於被我找到了,只需要在web.config中進行簡單配置,就可以達到動態產生靜態頁面的效果,同時又不影響Url重新導向。web.config中需要注意的配置節為<configuration>、<RewriteConfig>、<httpModules>、<httpHandlers>,在這些配置節裡邊都有注釋,容易看懂。
  <?xml version="1.0" encoding="utf-8"?>
  <!--
   注意: 除了手動編輯此檔案以外,您還可以使用
   Web 管理工具來配置應用程式的設定。可以使用 Visual Studio 中的
   “網站”->“Asp .Net 配置”選項。
   設定和注釋的完整列表在
   machine.config.comments 中,該檔案通常位於
   / Windows/Microsoft .Net/Framework/v2.x/Config 中
  -->
  <configuration>
  
   <!-- RUL重寫開始 -->
   <configSections>
   <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
   </configSections>
   <RewriterConfig>
   <Rules>
   <!--地址修正規則-->
   <!--首頁,定位到靜態頁面-->
   <RewriterRule>
   <Type>Static</Type>
   <LookFor>~/Default/.aspx</LookFor>
   <SendTo>~/Default.htm</SendTo>
   </RewriterRule>
   <!--二級頁面,定位到動態網頁面-->
   <RewriterRule>
   <Type>Dynamic</Type>
   <LookFor>~/List/.aspx</LookFor>
   <SendTo>~/Show.aspx</SendTo>
   </RewriterRule>
   </Rules>
   </RewriterConfig>
   <!-- RUL重寫結束 -->
  
   <appSettings/>
   <connectionStrings/>
   <system.web>
   <!--
   設定 compilation debug="true" 將偵錯符號插入
   已編譯的頁面中。但由於這會
   影響效能,因此只在開發過程中將此值
   設定為 true。
   -->
   <httpModules>
   <!--URL重寫-->
   <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
   </httpModules>
  
   <httpHandlers>
   <!--產生靜態頁面-->
   <add verb="*" path="*.aspx" validate="false" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>
   </httpHandlers>
  
   <compilation debug="false" />
   <!--
   通過 <authentication> 節可以配置 ASP.NET 使用的
   安全身分識別驗證模式,
   以標識傳入的使用者。
   -->
   <authentication mode="Forms" />
   <!--
   如果在執行請求的過程中出現未處理的錯誤,
   則通過 <customErrors> 節可以配置相應的處理步驟。具體說來,
   開發人員通過該節可以配置
   要顯示的 html 錯誤頁
   以代替錯誤堆疊追蹤。
  
   <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
   <error statusCode="403" redirect="NoAccess.htm" />
   <error statusCode="404" redirect="FileNotFound.htm" />
   </customErrors>
   -->
   <globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
   </system.web>
  </configuration>
  兩個關鍵的類是ModuleRewriter和RewriterFactoryHandler
  ModuleRewriter類用於Url重新導向,代碼如下:
  ModuleRewriter
  using System;
  using System.Text.RegularExpressions;
  using System.Configuration;
  using URLRewriter.Config;
  using System.Data;
  using System.Web;
  using System.Web.UI; 
namespace URLRewriter
  {
   /**//// <summary>
   /// Provides a rewriting HttpModule.
   /// </summary>
   public class ModuleRewriter : BaseModuleRewriter
   {
   /**//// <summary>
   /// This method is called during the module's BeginRequest event.
   /// </summary>
   /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
   /// <param name="app">The HttpApplication instance.</param>
   protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
   {
   //只對檔案尾碼為aspx頁面有效
   if (requestedPath.IndexOf(".aspx") != -1)
   {
   HttpContext httpContext = app.Context;
  
   // get the configuration rules
   RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
  
   // iterate through each rule
   for (int i = 0; i < rules.Count; i++)
   {
   // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
   string lookFor = "^" + RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].LookFor) + "$";
  
   // Create a regex (note that IgnoreCase is set)
   Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
  
   // See if a match is found
   if (re.IsMatch(requestedPath))
   {
   //aspx頁面重新導向到htm頁面且http資料轉送方式為“GET”
   if (rules[i].Type == WebType.Static && app.Context.Request.RequestType == "GET")
   {
   //靜態頁面路徑
   string htmlWeb = RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].SendTo);
   //靜態頁面的最後修改時間
   DateTime dt = System.IO.File.GetLastWriteTime(httpContext.Server.MapPath(htmlWeb));
   //目前時間和靜態頁面產生時間對比,如果時間小於一個小時,重新導向到靜態頁面
   if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0)
   {
   requestedPath = htmlWeb;
   }
   }
   else
   {
   requestedPath = rules[i].SendTo;
   }
  
   // Rewrite the URL
   RewriterUtils.RewriteUrl(httpContext, requestedPath);
   break; // exit the for loop
   }
   }
   }
   }
  
   }
  }
  CreateHtmFactoryHandler類用於產生靜態頁面,代碼如下:
  CreateHtmFactoryHandler
  using System;
  using System.IO;
  using System.Web.UI;
  using System.Web;
  using URLRewriter.Config;
  using System.Configuration;
  using System.Text.RegularExpressions;
  
  namespace URLRewriter
  {
   /**//// <summary>
   /// 依據web.config配置資訊,產生靜態頁面
   /// </summary>
   public class CreateHtmFactoryHandler : IHttpHandlerFactory
   {
   /**//// <summary>
   ///
   /// </summary>
   /// <param name="context">HttpContext 類的執行個體,它提供對用於為 HTTP 要求提供服務的內部 伺服器對象(如 Request、Response、Session 和 Server)的引用</param>
   /// <param name="requestType">用戶端使用的 HTTP 資料轉送方法(GET 或 POST)</param>
   /// <param name="url">所請求資源的 RawUrl。</param>
   /// <param name="pathTranslated">所請求資源的 PhysicalApplicationPath</param>
   /// <returns>返回實現 IHttpHandler 介面的類的執行個體</returns>
   public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
   {
   if (requestType == "GET")
   {
   // get the configuration rules
   RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
  
   // iterate through each rule
   for (int i = 0; i < rules.Count; i++)
   {
   // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
   string lookFor = "^" + RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].LookFor) + "$";
  
   // Create a regex (note that IgnoreCase is set)
   Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
  
   // See if a match is found
   if (re.IsMatch(url) && rules[i].Type == WebType.Static)
   {
   //得到要產生的靜態頁面的實體路徑
   string physicsWeb = context.Server.MapPath(RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].SendTo));
   //設定Response篩選器
   context.Response.Filter = new ResponseFilter(context.Response.Filter, physicsWeb);
   break;
   }
   }
   }
   //得到編譯執行個體
   return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
   }
  
   public virtual void ReleaseHandler(IHttpHandler handler)
   {
   }
   }
  }
  以上是兩個主要的類,還有一些輔助的類,我把 測試項目附上,裡邊有原始碼和樣本。
  點擊這裡 下載:原始碼和樣本
  聲明一下,我是在修改一個開源的項目(UrlRewrite)來實現上述功能。有關UrlRewrite介紹,請看這裡,ASP.NET 中執行 URL 重寫。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.