URL重写
第一步:新建项目
第二步:添加引用
1.引用URLRewriter.dll文件
第三步:新建ActionlessForm类,目的是为了处理URL回发
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace ActionlessForm
{
/// <summary>
/// The Form class extends the HtmlForm HTML control by overriding its RenderAttributes()
/// method and NOT emitting an action attribute.
/// </summary>
public class Form : System.Web.UI.HtmlControls.HtmlForm
{
/// <summary>
/// The RenderAttributes method adds the attributes to the rendered <form> tag.
/// We override this method so that the action attribute is not emitted.
/// </summary>
protected override void RenderAttributes(HtmlTextWriter writer)
{
// write the form's name
writer.WriteAttribute("name", this.Name);
base.Attributes.Remove("name");
// write the form's method
writer.WriteAttribute("method", this.Method);
base.Attributes.Remove("method");
// remove the action attribute
base.Attributes.Remove("action");
// finally write all other attributes
this.Attributes.Render(writer);
if (base.ID != null)
writer.WriteAttribute("id", base.ClientID);
}
}
}
在要处理回发的页面添加:<%@ Register TagPrefix="Skm" Namespace="ActionlessForm" Assembly="ActionlessForm"%> 并添加 <Skm:form id="Form1" runat="Server" action="test" >xxx</Skm:form>xxx代表任意服务器控件,如GridView
第四步:添加配置文件设置
如下:
<configSections>
<!-- The <configSections> element must contain a <section> tag for the <RewriterConfig> section element.
The type of the section handler is RewriterConfigSerializerSectionHandler, which is responsible for
deserializing the <RewriterConfig> section element into a RewriterConfig instance... -->
<section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
注:LookFor:要查找的模式,SendTo:用来替换模式的字符串
<RewriterConfig>
<Rules>
<!-- Rules for Blog Content Displayer -->
<RewriterRule>
<LookFor>~/(\d{4})/(\d{2})/(\d{2})\.aspx</LookFor>
<SendTo>~/ShowBlogContent.aspx?year=$1&month=$2&day=$3</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>~/(\d{4})/(\d{2})/Default\.aspx</LookFor>
<SendTo><![CDATA[~/ShowBlogContent.aspx?year=$1&month=$2]]></SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>~/(\d{4})/Default\.aspx</LookFor>
<SendTo>~/ShowBlogContent.aspx?year=$1</SendTo>
</RewriterRule>
<!-- Rules for Product Lister -->
<RewriterRule>
<LookFor>~/Products/Default\.aspx</LookFor>
<SendTo>~/ListCategories.aspx</SendTo>
</RewriterRule>
</RewriterConfig>
到此为止结束,有不足之处,请大家见谅,具体请查看MSDN网站:http://msdn2.microsoft.com/zh-cn/library/ms972974.aspx