VB.NET - 访问 My.MySettings.Default 更改 Thread.CurrentPrincipal?

发布于 2024-12-15 15:45:08 字数 818 浏览 6 评论 0原文

看来,当您在 VB.NET 中访问 My.Settings.Default 时,线程的 CurrentPrincipal 会发生变化。考虑以下代码。

            Dim name = "admin"
            Dim user = Membership.GetUser(name)
            Dim identity = New GenericIdentity(user.UserName)
            Dim principal = New RolePrincipal(identity)

            System.Threading.Thread.CurrentPrincipal = principal
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)
            Dim x = My.MySettings.Default
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)

这段代码的输出是

管理员

我的域名\我的用户名

这是预期的吗?它在任何地方都有记录吗?我找不到任何参考资料。

它似乎也只在第一次访问 My.MySettings.Default 时执行此操作,这意味着解决方法可能是在尝试设置线程的 CurrentPrincipal 之前触摸该属性以对其进行初始化。这样做会产生任何不良副作用吗?

It appears that when you access My.Settings.Default in VB.NET, your thread's CurrentPrincipal changes. Consider the following code.

            Dim name = "admin"
            Dim user = Membership.GetUser(name)
            Dim identity = New GenericIdentity(user.UserName)
            Dim principal = New RolePrincipal(identity)

            System.Threading.Thread.CurrentPrincipal = principal
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)
            Dim x = My.MySettings.Default
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)

The output of this code is

admin

MyDomain\MyUserName

Is this expected? Is it documented anywhere? I couldn't find any references to it.

It also seems to only do this the first time My.MySettings.Default is accessed, which means that a workaround might be to touch the property to initialize it before attempting to set the thread's CurrentPrincipal. Would there be any undesirable side effects to doing that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烂柯人 2024-12-22 15:45:09

我认为这是因为默认实例是使用线程安全操作创建的:

    Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)

由于默认实例仅在您第一次访问 MySettings 时创建,因此我认为最简单的解决方案是在更改用户身份之前访问它一次。

I believe that this is because the default instance is created using a thread-safe operation:

    Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)

Since the default instance is only created the first time you access MySettings, I think the easiest solution is to access it once prior to changing your user identity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文