简体   繁体   English

是否可以对ViewState进行自定义实现?

[英]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). Asp.Net具有一些选项来影响其ViewState页面的生成方式(加密,添加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? 这可能吗?

Yes, it's possible. 是的,有可能。 For instance, I built a view state compression logic based on some articles you can find on CodeProject. 例如,我根据您在CodeProject上可以找到的一些文章构建了视图状态压缩逻辑。 You'll need to override PageStatePersister from Page and create a class derivated from PageStatePersister : 您需要从Page重写PageStatePersister ,并创建一个从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. 是的,您需要实现自己的PageStatePersister类。 The MSDN page shows you an example of how it works. MSDN页面显示了其工作方式的示例。

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. 我们有一个相当大的ViewState,我们将其卸载到文件系统,并在实际页面上将其替换为更加紧凑的GUID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM