ASP.NET store Viewstate data in Session


Consider you have a web control as an assembl y and you dont have the source code of this . And the control store its data in viewstate and that data is really big. You can not able to change viewstate usage for this control . And much worse you have to use this important control.Thats may be help you to reduce output and use viewstate process at same time.

I mean you can use viewstate and store in session and reduce the weight of output.Ok that cost as server resources. And I dont really discuss it is proper or efficent or not. I Just show how to do it.

My other article about viewstate deal with compression and how to override base page functions of
LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium
I also use that functions in this article.
https://blog.bugrapostaci.com/2010/02/02/asp-net-compress-viewstate/

We are using one unique session key as path  for each page in session like
 Session[“ViewState_” + this.Request.Path]
You should better if you define a specific Guid value in your pages and use it for Session key.

protected override object LoadPageStateFromPersistenceMedium()
{
    string viewState = string.Empty;
    // try to get state data form Session.
    viewState = Session["ViewState_" + this.Request.Path] != null ? Session["ViewState_"
                      + this.Request.Path].ToString() : string.Empty;
 
    // Decompress the encoded and compressed state data than return it.
    byte[] bytes = Convert.FromBase64String(viewState);
    bytes = Utilities.MemoryCompressor.Decompress(bytes);
    LosFormatter formatter = new LosFormatter();
    return formatter.Deserialize(Convert.ToBase64String(bytes));
}
protected override void SavePageStateToPersistenceMedium(object state)
{
    //Encode state data
    LosFormatter formatter = new LosFormatter();
    StringWriter writer = new StringWriter();
    formatter.Serialize(writer, state);
    string viewStateString = writer.ToString();
    byte[] bytes = Convert.FromBase64String(viewStateString);
    bytes = Utilities.MemoryCompressor.Compress(bytes);
    //Save to session
    if (Session["ViewState_" + this.Request.Path] != null)
        Session["ViewState_" + this.Request.Path] = Convert.ToBase64String(bytes);
    else
        Session.Add("ViewState_" + this.Request.Path, Convert.ToBase64String(bytes));
}
Happy Codding...
Advertisement

About bpostaci
Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: