asp.net - 扩展 System.Web.HttpContext.User

标签 asp.net vb.net inheritance genericprincipal

我想扩展 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.asax Application_AuthenticateRequest 函数中设置对象,如下所示:

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

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

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

我也尝试过 CType 但它不起作用...我的错误是

[InvalidCastException: Unable to cast object of type 'System.Security.Principal.GenericPrincipal' to type 'myProject.CurrentUser'.]

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

有人吗?

最佳答案

您可以使用所需的属性创建自己的Principal 类,该类继承自通用Principal,然后将当前上下文的User 属性设置为该类型的用户。

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

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

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

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

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

可能还有其他解决方案!

关于asp.net - 扩展 System.Web.HttpContext.User,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/955107/

相关文章:

vb.net - 子接口(interface)的Load(x)函数隐藏父接口(interface)的Load()函数

c++ - 如何在虚拟继承下游使用参数化基类构造函数

asp.net - Razor 代码去哪儿了?

asp.net - 可以在 .NET Framework 和 .NET Core 之间共享的类库

vb.net - datagridview 中的多项选择

vb.net - 自动滚动到多行文本框的底部

jquery - 同步XMLHttpRequest..asp.net mvc

asp.net - EF5 Code First ALTER TABLE 语句与 FOREIGN KEY 约束冲突

vb.net - 拥有需要转换为 VB.net 的旧版 VB6 代码

java - 我的类应该是什么类型才能访问类及其扩展的类?