打印本文 打印本文 关闭窗口 关闭窗口
Taking a Bite Out of ASP.NET ViewState
作者:武汉SEO闵涛  文章来源:敏韬网  点击数3084  更新时间:2009/4/23 10:46:57  文章录入:mintao  责任编辑:mintao
EAA3B32A6AE813ECEECD28DEA66A 23BEE42193729BD48595EBAFE2C2E765BE77E006330BC3B1392D7C73F" />

The System.Security.Cryptography namespace includes the RNGCryptoServiceProvider class that you can use to generate this string, as demonstrated in the following GenerateCryptoKey.aspx sample:

<%@ Page Language="c#" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<HTML>
    <body>
        <form runat="server">
        <H3>Generate Random Crypto Key</H3>
        <P>
            <asp:RadioButtonList id="RadioButtonList1" 
            runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Value="40">40-byte</asp:ListItem>
                <asp:ListItem Value="128" Selected="True">128-byte</asp:ListItem>
            </asp:RadioButtonList>&nbsp;
            <asp:Button id="Button1" runat="server" onclick="GenerateKey"
            Text="Generate Key">
            </asp:Button></P>
        <P>
            <asp:TextBox id="TextBox1" runat="server" TextMode="MultiLine" 
            Rows="10" Columns="70" BackColor="#EEEEEE" EnableViewState="False">
            Copy and paste generated results</asp:TextBox></P>
        </form>
    </body>
</HTML>


<script runat=server>

   void GenerateKey(object sender, System.EventArgs e)
   {
       int keylength = Int32.Parse(RadioButtonList1.SelectedItem.Value);
       
      // Put user code to initialize the page here
        byte[] buff = new Byte[keylength/2];

        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        // The array is now filled with cryptographically strong random bytes
        rng.GetBytes(buff);

        StringBuilder sb = new StringBuilder(keylength);
        int i;
        for (i = 0; i < buff.Length; i++) {
            sb.Append(String.Format("{0:X2}",buff[i]));
        }
        
        // paste to the textbox to the user can copy it out
        TextBox1.Text = sb.ToString();
    }

</script>

Summary

ASP.NET ViewState is a new kind of state service that developers can use to track UI state on a per-user basis. There''''s nothing magical about it. It simply takes an old Web programming trick—roundtripping state in a hidden form field—and bakes it right into the page-processing framework. But the result is pretty wonderful—a lot less code to write and maintain in your Web-based forms.

You won''''t always need it, but when you do, I think you''''ll find ViewState is a satisfying addition to the feast of new features ASP.NET offers to page developers.


Susan Warren is a program manager for ASP.NET on the .NET Framework team.

上一页  [1] [2] [3] [4] 

打印本文 打印本文 关闭窗口 关闭窗口