gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:59:32 26 4
gpt4 key购买 nike

我想扩展 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com