ASP.NET中的页面范围变量

arl*_*len 2 asp.net

我需要访问Web应用程序页面中的一些变量.变量的范围就在该特定页面中.哪一个是解决方案?Session或ViewState?还是更好的解决方案?

 Private Property UserId() As Integer
            Get
                If Not ViewState("UserId") Is Nothing Then
                    Return CType(ViewState("UserId"), Integer)
                Else
                    Return -1
                End If

            End Get
            Set(ByVal Value As Integer)
                ViewState("UserId") = Value
            End Set
        End Property
Run Code Online (Sandbox Code Playgroud)

要么

Private Property UserId() As Integer
    Get
        If Not Session("UserId") Is Nothing Then
            Return CType(Session("UserId"), Integer)
        Else
            Return -1
        End If

    End Get
    Set(ByVal Value As Integer)
        Session("UserId") = Value
    End Set
End Property
Run Code Online (Sandbox Code Playgroud)

每个用户也是ViewState自定义吗?

wsa*_*lle 7

如果您要在多个页面中存储用户独有的信息,那么Session是一个不错的选择.Cookie用于将用户绑定到给定的Session,Sessions将超时,这是需要记住的.

ViewState只是HTML中的一个隐藏字段,因此当页面回发给自己时,它可用于持久保存对象.缺点是你将数据序列化为一个字符串并将其发送到客户端(它在回发后验证,因此篡改它会引发异常).要回答您的问题,是的,ViewState是每页用户数.

如果您需要存储站点的所有用户访问的数据,则应用程序存储或HttpContext.Cache非常有用.

这只是一个快速摘要,有关选项的更详细说明,请查看ASP.NET状态管理概述.