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;
        }
    }
}

Need Your Help

Does scalatra use circumflex behind the scenes?

rest scala scalatra

Does scalatra use circumflex behind the scenes (or vise versa)? What are the key differences between them, and which one would you use?

WebKitErrorDomain while integrating facebook ios sdk in my ios application. Using Dialog Feed to post on wall

ios facebook integration

I m using facebook ios sdk from github, for integrating facebook in my iPhone application. I m trying to share something in the wall. When I click share, it goes to facebook, does single sign on lo...