在网站根目录创建App_Browsers目录,在里面建立一个新的文件起名 RewriteForm.browser ,其内容如下:
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.HtmlControls.HtmlForm"
adapterType="Kuang.HtmlFormAdapter" />
</controlAdapters>
</browser>
</browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.HtmlControls.HtmlForm"
adapterType="Kuang.HtmlFormAdapter" />
</controlAdapters>
</browser>
</browsers>
其中,browser节的 refID="Default" 属性是表示扩展系统原有的Default.browser文件(位于 %windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers ),Default.browser 是全部浏览器定义的根,具体细节请参考MSDN说明。
Adapter的意思是适配器,在.NET领域表示在两个对象之间进行协调的对象,例如ADO.NET中众所周知的SqlDataAdapter类就是在SqlCommand和DataSet之间协调的Adapter。
ASP.NET 2.0带来了ControlAdapter的概念,意思是位于
ControlAdapter并没有什么特殊的功能,只不过和重载Page类的方法相比较,前者提供了重载Web控件Render方法的能力而又不需要继承该控件,并且可以只针对特定的控件例如这里的HtmlForm类。而在马哥的方法中,如果有别的控件也用了action属性,就会被错误的改写。在
下面这个是自定义的ControlAdapter类的代码:
using System;
using System.Web.UI.Adapters;
namespace Kuang {
public class HtmlFormAdapter : ControlAdapter {
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
base.Render(new FormRewriteTextWriter(writer));
}
}
}
using System.Web.UI.Adapters;
namespace Kuang {
public class HtmlFormAdapter : ControlAdapter {
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
base.Render(new FormRewriteTextWriter(writer));
}
}
}
和重载Page类的手段一样,这段代码也引用了一个自定义的 HtmlTextWriter 类,以下是该类的实现代码,我自己做了一定的修改:
using System;
using System.IO;
using System.Web;
using System.Web.UI;
namespace Kuang {
public class FormRewriteTextWriter : HtmlTextWriter {
public FormRewriteTextWriter(TextWriter writer) : base(writer) {
if(writer is HtmlTextWriter)
this.InnerWriter = (writer as HtmlTextWriter).InnerWriter;
else
this.InnerWriter = writer;
}
public override void WriteAttribute(string name, string value, bool fEncode) {
HttpContext context = HttpContext.Current;
object rewroteAlready = context.Items["FormActionRewroteAlready"];
if(name == "action" && rewroteAlready == null) {
value = context.Request.RawUrl;
context.Items["FormActionRewroteAlready"] = new object();
}
base.WriteAttribute(name, value, fEncode);
}
}
}
using System.IO;
using System.Web;
using System.Web.UI;
namespace Kuang {
public class FormRewriteTextWriter : HtmlTextWriter {
public FormRewriteTextWriter(TextWriter writer) : base(writer) {
if(writer is HtmlTextWriter)
this.InnerWriter = (writer as HtmlTextWriter).InnerWriter;
else
this.InnerWriter = writer;
}
public override void WriteAttribute(string name, string value, bool fEncode) {
HttpContext context = HttpContext.Current;
object rewroteAlready = context.Items["FormActionRewroteAlready"];
if(name == "action" && rewroteAlready == null) {
value = context.Request.RawUrl;
context.Items["FormActionRewroteAlready"] = new object();
}
base.WriteAttribute(name, value, fEncode);
}
}
}
把以上两段代码放入到网站的App_Code目录下,就大功告成了,这个方法一个特别的优点是,不需要改动原来网站的任何代码,连 web.config 都不用改。