C#伪静态实现的方法

时间:2023-03-10 01:40:19
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=$]]></SendTo>
</RewriterRule> <RewriterRule>
<LookFor><![CDATA[~/tupian/(\d+)/.html]]></LookFor>
<SendTo><![CDATA[~/web/admin/other/$.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