3

我想扩展 System.Web.HttpContext.User 对象(ASP.NET/VB.NET),以便它包含除名称之外的其他字段。我知道我可以创建一个继承 System.Security.Principal.GenericPrincipal 类的对象,但是如何以可用的方式将其存储在 Current.User 对象中。即,我可以做类似的事情Current.User.UserID

到目前为止,为了实现这一点,我已经通过使用 | 创建了一个笨拙的解决方法。在 User.Name 属性中分隔字符串,然后拆分它们,但这有点荒谬。

有什么建议么?

谢谢!

编辑:我尝试了以下方法无济于事:

Imports System.Security.Principal
Public Class CurrentUser : Inherits GenericPrincipal
Private _totalpoints As Integer
Private _sentencecount As Integer
Private _probationuntil As DateTime
Public ReadOnly Property TotalPoints() As Integer
    Get
        Return _totalpoints
    End Get
End Property
Public ReadOnly Property SentenceCount() As Integer
    Get
        Return _sentencecount
    End Get
End Property
Public ReadOnly Property ProbationUntil() As DateTime
    Get
        Return _probationuntil
    End Get
End Property
Public Sub New(ByVal principle As IIdentity, ByVal roles() As String, _
ByVal points As Integer, ByVal sentences As Integer, ByVal probationTil As DateTime)
    MyBase.New(principle, roles)
    _totalpoints = points
    _sentencecount = sentences
    _probationuntil = FixDBNull(probationTil)
End Sub
End Class

在我的 Global.asaxApplication_AuthenticateRequest函数中设置对象,如下所示:

HttpContext.Current.User = New CurrentUser(User, userRoles, _
 points, sentenceCount, probationUntil)

在需要对象的地方直接转换,如下所示:

Dim thisUser As CurrentUser = DirectCast(Current.User, CurrentUser)

我也尝试过 CType,但它没有用......我的错误是

[InvalidCastException:无法将“System.Security.Principal.GenericPrincipal”类型的对象转换为“myProject.CurrentUser”类型。]

我在这里失去理智...... :(谢谢大家......

任何人?

4

2 回答 2

3

您可以创建自己的具有所需属性的 Principal 类,该类继承自 Generic Principal,然后将 Current Context 的 User 属性设置为该类型的用户。

下面的示例适用于 ASP.Net MVC,但类似的方法也可用于 Web 表单。

您可以在用户通过身份验证后在 PostAuthenticateRequest 中执行此操作(在 Global.asax 中)

private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
     SomePrincipal newUser = new SomePrincipal(User.Identity, tmpRoles);

                senderRef.Context.User = newUser;
                System.Threading.Thread.CurrentPrincipal = newUser;
}

然后,您可以在页面(或控制器)的基类中添加一个属性或方法,例如将 Context.User 主体包装并键入您的 Principal 类型,并确保您调用它而不是调用 HttpContext 上的那个。

可能还有其他解决方案!

于 2009-06-05T10:08:03.860 回答
2

这种方法对你有用吗?它看起来有点复杂,但设置起来确实不需要太长时间:

  1. 创建您自己的“基”类,并让您的页面继承自该类。例如,创建一个名为“BasePage”的基类,它继承自 System.Web.UI.Page。

  2. 让您的 ASP.net 页面从您的新 BasePage 类继承。

  3. 在 BasePage 类中,您可以拥有一个公共属性,其中包含您要为用户存储的额外字段(例如 BasePage.FirstName、BasePage.LastName)。更好的是,创建一个包含额外字段的用户对象,并通过 BasePage 公开它,例如。“基本页面.客户”。如果您打算稍后扩展 BasePage,这会使事情保持整洁。

  4. 然后,您可以覆盖基类的 OnInit() 以检查 HTTPContext.Current.User.Name 属性,并从您的数据库中获取必要的信息来初始化您的自定义属性。

您可以修改代码,以便在每次刷新页面时都不需要访问数据库,方法是使用 ControlState 检查自定义字段是否具有值,然后再从数据库中再次填充它们。

希望这可以帮助...

理查德。

于 2009-06-05T10:07:53.627 回答