c# - Thread.CurrentPrincipal 重置为默认的 GenericPrincipal

标签 c# wpf claims current-principal

在初始化我的应用程序期间,我设置了 System.Threading.Thread.CurrentPrincial。但是在应用程序初始化后,我想访问这个 Principal,CurrentPrincipal 再次包含默认的 GenericPrincipal。

有人知道我为什么会出现这种行为吗?以及我必须如何设置 Principal 以便在应用程序初始化后访问它。

以下示例演示了该行为:

主窗口.xaml:

<Window x:Class="PrincipalTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
   <Grid>
       <Button Click="ButtonClick"/>
   </Grid>
</Window>

主窗口.xaml.cs:

using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Claims;
using System.Threading;
using System.Windows;

namespace PrincipalTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Debug.WriteLine("Principal Type: {0}", Thread.CurrentPrincipal.GetType()); // Principal Type: System.Security.Principal.GenericPrincipal
            Thread.CurrentPrincipal = new ClaimsPrincipal();
            Debug.WriteLine("Principal Type: {0}", Thread.CurrentPrincipal.GetType()); // Principal Type: System.Security.Claims.ClaimsPrincipal
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Principal Type: {0}", Thread.CurrentPrincipal.GetType()); // Principal Type: System.Security.Principal.GenericPrincipal
        }
    }
}

在我的实际项目中,我在 Bootstrapper 中设置了 Thread.CurrentPrincipal 属性。

最佳答案

你必须使用 AppDomain.CurrentDomain.SetThreadPrincipal()

CurrentPrincipal 在 Window.Loaded 后重置为默认值 (GenericPrincipal)

关于c# - Thread.CurrentPrincipal 重置为默认的 GenericPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23126176/

相关文章:

c# - 在后面的代码中访问 ViewModel 是否总是违反 MVVM 模式?

.net - 在ASP.NET中生成图像缩略图?

c# - 如何从 token 中提取并获取声明?

jwt - 添加访问 token key 斗篷的声明

c# - 3 层架构引用

c# - 我们可以在 C# 对象上实现 Transaction 吗?

wpf - WPF 中的命令绑定(bind)内存泄漏

c# - Azure AD - 通过图形服务或声明获取组 AD 名称

c# - 在 .NET DLL 中包装 32 位 native DLL 以在 64 位 .NET 应用程序中使用

c# - 这是有效的德国日期时间文化格式吗?