C#偽靜態實現的方法


 

  在asp.net開發網站的時候,我們經常會用到偽靜態,好處是可以隱藏真實的路徑,提高網站的安全性,在官網等展示網站希望對搜索引擎友好,提高搜索排名;或者在涉及到模板開發都會用到偽靜態。下面講解下平時用到的偽靜態實現方法。

一、方法一:

  使用URLRewriter.dll下載地址:http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi

  1在啟動文件中添加URLRewriter.dll文件引用,然后在web.config文件configuration節點下添加一下代碼

<configSections>
    <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
  </configSections>

  2在system.web節點下添加一下代碼

<compilation>
      <buildProviders>
        <add extension=".html" type="System.Web.Compilation.PageBuildProvider"/>
      </buildProviders>
    </compilation>


<httpHandlers> <add verb="*" path="*.html" type="System.Web.UI.PageHandlerFactory"/> </httpHandlers> <httpModules> <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter"/> </httpModules>

 

  3在configuration節點下添加一下重寫url代碼(正則表達式)

<RewriterConfig>
    <Rules>
        
      <RewriterRule>
        <LookFor><![CDATA[~/shop/(\w+)?]]></LookFor>
        <SendTo><![CDATA[~/vshop/wechat/order/index.aspx?uid=$1]]></SendTo>
      </RewriterRule>

      
      <RewriterRule>
        <LookFor><![CDATA[~/tupian/(\d+)/.html]]></LookFor>
        <SendTo><![CDATA[~/web/admin/other/$1.ashx]]></SendTo>
      </RewriterRule>
        
    </Rules>
  </RewriterConfig>

二、方法二
在.net3.5版本開始,提供了System.Web.Routing,程序可以自己寫偽靜態方法

添加一個ReWriteUrl.cs文件,代碼如下:

public class ReWriteUrl : IRouteHandler { public string UrlRote { get; private set; } public ReWriteUrl (string sUrlRote) { UrlRote = sUrlRote; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { return BuildManager.CreateInstanceFromVirtualPath(UrlRote, typeof(IHttpHandler)) as IHttpHandler; } }

 

在Global.asax.cs文件下的Application_Start函數里

 

 protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.Add( new Route("xxxx.html", new ReWriteUrl("~/xxxx.ashx")));//地址重寫
        }

.net技術交流QQ群:320128737

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM