rivate static readonly Regex endFormRegex = new Regex(@"</form>", RegexOptions.Multiline | RegexOptions.Compiled);
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
Match viewStateMatch = viewStateRegex.Match(html);
string viewStateString = viewStateMatch.Captures[0].Value;//找出ViewState的Html标记
html = html.Remove(viewStateMatch.Index, viewStateMatch.Length);//替换掉ViewState的html标记
Match endFormMath = endFormRegex.Match(html, viewStateMatch.Index);
html = html.Insert(endFormMath.Index, viewStateString);//将ViewState的Html标记插入到</form>标记之前
writer.Write(html);
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
最后生成的Html页面的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
调整ViewState的位置,让你的asp.net页面对搜索引擎更友好
</title></head>
<body>
<form name="form1" method="post" action="Top.aspx" id="form1">
<div>
</div>
<div>
</div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzgzNDMwNTMzZGTKRk3xYdpqlKIfqyg44evx9dxYpQ==" /></form>
</body>
</html>最后的结果大家也看到了,确实移动了ViewState的html标记的位置,这样对搜索引擎更友好。 |