关于把asp.net中ViewState 移动到页面底部的好处,这个都不需要说了。
1.更容易被搜索引擎收录。
2.页面速度好像也有所提高.
但当页面又GridView 排序和分页将出现问题。????
思考中。
看看有没有什么办法可以解决!
关于asp.net怎么把ViewState移动页面底部,给段代码大家参考。
1.新建个
HttpModule 代码如下。
2.//在web.config插入下面 modules
<httpModules>
<add name="ViewstateModule" type="blogjava.Net.ViewstateModule" />
</httpModules>
</system.web>
他的原理就是在请求是aspx页面得时候,的到请求得数据(网页得源代码)再根据网页源代码用字符串查找方式查找"input type=\"hidden\" name=\"__VIEWSTATE\ 再把他移动到底部。看覆盖得Write 方法就一目了然了。
#region Using
using System;
using System.IO;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
#endregion
namespace Blogjava.Net
{
/// <summary>
/// Removes whitespace from the webpage.
/// </summary>
public class ViewstateModule : IHttpModule
{
#region IHttpModule Members
void IHttpModule.Dispose()
{
// Nothing to dispose;
}
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
#endregion
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app.Request.Url.OriginalString.Contains(".aspx"))
{
app.Response.Filter = new ViewstateFilter(app.Response.Filter);
}
}
#region Stream filter
private class ViewstateFilter : Stream
{
public ViewstateFilter(Stream sink)
{
_sink = sink;
}
private Stream _sink;
#region Properites
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
_sink.Flush();
}
public override long Length
{
get { return 0; }
}
private long _position;
public override long Position
{
get { return _position; }
set { _position = value; }
}
#endregion
#region Methods
public override int Read(byte[] buffer, int offset, int count)
{
return _sink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _sink.Seek(offset, origin);
}
public override void SetLength(long value)
{
_sink.SetLength(value);
}
public override void Close()
{
_sink.Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
byte[] data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
string html = System.Text.Encoding.Default.GetString(buffer);
int startPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"");
if (startPoint >= 0)
{
int endPoint = html.IndexOf("/>", startPoint) + 2;
string viewstateInput = html.Substring(startPoint, endPoint - startPoint);
html = html.Remove(startPoint, endPoint - startPoint);
int formEndStart = html.IndexOf("</form>") - 1;
if (formEndStart >= 0)
{
html = html.Insert(formEndStart, viewstateInput);
}
}
byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
_sink.Write(outdata, 0, outdata.GetLength(0));
}
#endregion
}
#endregion
}
}
参考:
http://www.hanselman.com/blog/ZippingCompressingViewStateInASPNET.aspx//end