Question

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?

Était-ce utile?

La solution

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top