Is it possible to make a custom implementation of ViewState?

Asp.Net has some options to influence the ways a page its ViewState is generated (encryption, adding of a mac, ViewStateUserKey).

I would like to do it myself, not based on configuration, but on my own class that used other algorithms for serialization and encryption. Is this possible?

Answers


Yes, it's possible. For instance, I built a view state compression logic based on some articles you can find on CodeProject. You'll need to override PageStatePersister from Page and create a class derivated from PageStatePersister:

// In your page:
protected override PageStatePersister PageStatePersister
{
   get { return new ViewStateCompressor(this); }
}

And create a new class:

public class ViewStateCompressor : PageStatePersister
{
    private const string ViewStateKey   = "__VSTATE";
    public ViewStateCompressor(Page page) : base(page)
    {
    }

    private LosFormatter stateFormatter;
    protected new LosFormatter StateFormatter
    {
        get { return this.stateFormatter ?? (this.stateFormatter = new LosFormatter()); }
    }

    public override void Save()
    {
        using (StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
        {
            // Put viewstate data on writer
            StateFormatter.Serialize(writer, new Pair(base.ViewState, base.ControlState));

            // Handle your viewstate data
            // byte[] bytes = Convert.FromBase64String(writer.ToString());

            // Here I create another hidden field named "__VSTATE"
            ScriptManager.RegisterHiddenField(Page, ViewStateKey, Convert.ToBase64String(output.ToArray()));
        }
    }

    public override void Load()
    {
        byte[] bytes = Convert.FromBase64String(base.Page.Request.Form[ViewStateKey]);
        using (MemoryStream input = new MemoryStream())
        {
            input.Write(bytes, 0, bytes.Length);
            input.Position = 0;

            // Handle your viewstate data

            Pair p = ((Pair)(StateFormatter.Deserialize(Convert.ToBase64String(output.ToArray()))));
            base.ViewState = p.First;
            base.ControlState = p.Second;
        }
    }
}

Yes you need to implement your own PageStatePersister class. The MSDN page shows you an example of how it works.

We had a rather large ViewState we offloaded to the file system and replaced it with a much more compact GUID on the actual page.


Need Your Help

html5 tag <video> does not work in safari and IE

html5 internet-explorer video safari webm

I have a webm video running on my site which is not working on safari and IE.

Get list of routes of a Flask function

python twitter-bootstrap dynamic flask

I am using Flask and Bootstrap 3, I would like to get a list of all the urls generated by a function, so that I can link to all of them in the bootstrap theme .