Đối với những gì nó có giá trị, đây là mã tôi đã kết thúc bằng cách sử dụng để giải quyết vấn đề lớn hình ảnh trong tầm tay: di chuyển viewstate ra khỏi html. Chỉ cần bật này vào mypage.aspx.cs của bạn:
// Inspired by: http://aspalliance.com/72
const string ViewStateFieldName = "__VIEWSTATEKEY";
const string RecentViewStateQueue = "RecentViewStateQueue";
const int RecentViewStateQueueMaxLength = 5;
protected override object LoadPageStateFromPersistenceMedium()
{
// The cache key for this viewstate is stored where the viewstate normally is, so grab it
string viewStateKey = Request.Form[ViewStateFieldName] as string;
if (viewStateKey == null) return null;
// Grab the viewstate data from the cache using the key to look it up
string viewStateData = Cache[viewStateKey] as string;
if (viewStateData == null) return null;
// Deserialise it
return new LosFormatter().Deserialize(viewStateData);
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
// Serialise the viewstate information
StringBuilder _viewState = new StringBuilder();
StringWriter _writer = new StringWriter(_viewState);
new LosFormatter().Serialize(_writer, viewState);
// Give this viewstate a random key
string viewStateKey = Guid.NewGuid().ToString();
// Store the viewstate in the cache
Cache.Add(viewStateKey, _viewState.ToString(), null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(Session.Timeout), CacheItemPriority.Normal, null);
// Store the viewstate's cache key in the viewstate hidden field, so on postback we can grab it from the cache
ClientScript.RegisterHiddenField(ViewStateFieldName, viewStateKey);
// Some tidying up: keep track of the X most recent viewstates for this user, and remove old ones
var recent = Session[RecentViewStateQueue] as Queue<string>;
if (recent == null) Session[RecentViewStateQueue] = recent = new Queue<string>();
recent.Enqueue(viewStateKey); // Add this new one so it'll get removed later
while (recent.Count > RecentViewStateQueueMaxLength) // If we've got lots in the queue, remove the old ones
Cache.Remove(recent.Dequeue());
}
Và đối với một cách siêu đơn giản của việc sử dụng các SessionPageStatePersister, một lần nữa đặt này trong mypage.aspx.cs của bạn:
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
đã coi bạn lưu trữ ViewState trong DB thay vì phiên, điều này sẽ dễ dàng hơn và cũng có quy mô tốt hơn nhiều – Daveo
RPM: viewstate đã được tuần tự hóa nên không có sự khác biệt. RAM trên máy chủ của tôi nhanh hơn rất nhiều so với việc gửi 100kb viewstate cả hai cách trên các kết nối mạng Úc. – Chris
daveo: Db sẽ chậm hơn ram. Chia tỷ lệ không phải là vấn đề - không phải loại trang web đó. – Chris