asp.net 处理原文件中过长的viewstate代码
程序员文章站
2024-03-08 10:42:10
复制代码 代码如下: public class xvpage : page { static private directoryinfo _dir; private dir...
复制代码 代码如下:
public class xvpage : page
{
static private directoryinfo _dir;
private directoryinfo dir
{
get
{
if (_dir == null)
{
_dir = new directoryinfo(path.combine(appdomain.currentdomain.basedirectory, "app_data"));
if (!_dir.exists)
_dir.create();
_dir = new directoryinfo(path.combine(_dir.fullname, "viewstate"));
if (!_dir.exists)
_dir.create();
}
return _dir;
}
}
protected override object loadpagestatefrompersistencemedium()
{
pagestatepersister ps = this.pagestatepersister;
ps.load();
if (ps.controlstate != null)
ps.controlstate = antiserialization((string)ps.controlstate);
if (ps.viewstate != null)
ps.viewstate = antiserialization((string)ps.viewstate);
return new pair(ps.controlstate, ps.viewstate);
}
protected override void savepagestatetopersistencemedium(object state)
{
pagestatepersister ps = this.pagestatepersister;
if (state is pair)
{
pair pair = (pair)state;
ps.controlstate = pair.first;
ps.viewstate = pair.second;
}
else
{
ps.viewstate = state;
}
if (ps.controlstate != null)
ps.controlstate = antiserialization(ps.controlstate);
if (ps.viewstate != null)
ps.viewstate = antiserialization(ps.viewstate);
ps.save();
}
private object antiserialization(string stateid)
{
string statestr = (string)cache[stateid];
string file = path.combine(dir.fullname, stateid);
if (statestr == null)
statestr = file.readalltext(file);
else
cache.remove(stateid);
return new objectstateformatter().deserialize(statestr);
}
private string antiserialization(object obj)
{
string value = new objectstateformatter().serialize(obj);
string stateid = (datetime.now.ticks + (long)value.gethashcode()).tostring(); //产生离散的id号码
file.writealltext(path.combine(dir.fullname, stateid), value);
cache.insert(stateid, value);
return stateid;
}
protected override void onunload(eventargs e)
{
base.onunload(e);
datetime dt = datetime.now.addminutes(-20);
foreach (fileinfo fl in dir.getfiles())
if (fl.lastaccesstime < dt)
try
{
fl.delete();
}
catch
{
}
}
}
只需要在页面后台中继承xvpage 就可以了
public partial class index_content : xvpage