使用UrlRewriter.NET重写URL
使用的是Intelligencia出品的开源组件UrlRewriter.NET。
1.web.config配置
<configSections>
<section name="rewriter"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler,
Intelligencia.UrlRewriter" />
</configSections>
<rewriter>
<rewrite url="^/User/(\d+)$" to="~/User.aspx?id=$1" processing="stop" />
<rewrite url="^/User/(\w+)$" to="~/User.aspx?name=$1" processing="stop" />
</rewriter>
<system.web>
<httpModules>
<add name="UrlRewriter"
type="Intelligencia.UrlRewriter.RewriterHttpModule,
Intelligencia.UrlRewriter" />
</httpModules>
</system.web>
2.在UrlRewirter后保持PostBack地址
代码
namespace Sample.Web.UI.Adapters
{
public class FormRewriterControlAdapter :
System.Web.UI.Adapters.ControlAdapter
{
protected override void Render(HtmlTextWriter writer)
{
base.Render(new RewriteFormHtmlTextWriter(writer));
}
}
public class RewriteFormHtmlTextWriter : HtmlTextWriter
{
public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
: base(writer)
{
this.InnerWriter = writer.InnerWriter;
}
public RewriteFormHtmlTextWriter(TextWriter writer)
: base(writer)
{
this.InnerWriter = writer;
}
public override void WriteAttribute(string name, string value, bool fEncode)
{
if (name == "action")
{
HttpContext context = HttpContext.Current;
if (context.Items["ActionAlreadyWritten"] == null)
{
value = context.Request.RawUrl;
context.Items["ActionAlreadyWritten"] = true;
}
}
base.WriteAttribute(name, value, fEncode);
}
}
}
要让这个Control Adaptor生效,还必须在Web项目中创建一个browser文件,例如“App_Browsers\Form.browser”,在里面写入如下代码
代码
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.HtmlControls.HtmlForm"
adapterType="Sample.Web.UI.Adapters.FormRewriterControlAdapter" />
</controlAdapters>
</browser>
</browsers>
更多资料查看UrlRewriter.NET官网
在这里感谢下老赵在他那学习到很多东西。