ASP.NET偽靜態實現

來源:互聯網
上載者:User

標籤:bsp   toc   ref   system   end   tracking   namespace   pattern   efault   

在asp.net下,如何自己寫代碼來實現偽靜態呢?如何重寫url地址呢?

 

例如:本來aspx的頁面地址是:/default.aspx?id=1,我要重寫成這樣:/index-1.html。那如何??

 

思路如下:利用HttpModule來實現。

 

1.建立檔案,URLHttpModel.cs,並實現IHttpModule介面。代碼如下:

 

[csharp] view plain copy 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text.RegularExpressions;  
  5. using System.Web;  
  6.   
  7. namespace Web.HttpModel.Demo  
  8. {  
  9.     public class URLHttpModel : IHttpModule  
  10.     {  
  11.         public void Init(HttpApplication context)  
  12.         {  
  13.             context.BeginRequest += Context_BeginRequest;  
  14.         }  
  15.   
  16.         private void Context_BeginRequest(object sender, EventArgs e)  
  17.         {  
  18.             HttpApplication app = (HttpApplication) sender;  
  19.             HttpContext context = app.Context;  
  20.             string requestPage = context.Request.Path.ToLower();  
  21.             var newPattern = "/index-(\\d+).html";  
  22.             if (Regex.IsMatch(requestPage, $"^{newPattern}$", RegexOptions.None | RegexOptions.IgnoreCase))  
  23.             {  
  24.                 string queryString = Regex.Replace(requestPage, newPattern, "id=$1", RegexOptions.None | RegexOptions.IgnoreCase);  
  25.                 context.RewritePath("/Default.aspx", string.Empty, queryString);  
  26.             }  
  27.         }  
  28.   
  29.         public void Dispose()  
  30.         {  
  31.               
  32.         }  
  33.     }  
  34. }  

 

2.然後在web.config檔案中,配置此Modeule,代碼如下:

 

[csharp] view plain copy 
  1. <httpModules>  
  2.       <add name="URLModel" type="Web.HttpModel.Demo.URLHttpModel,Web.HttpModel.Demo"/>  
  3. </httpModules>  

3,然後運行項目,輸入如下地址,/index-1.html,可以看到如下的效果:

 

  

ASP.NET偽靜態實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.