Thread.CurrentPrincipal重置为默认GenericPrincipal

时间:2014-04-17 06:35:46

标签: c# wpf claims current-principal

在初始化我的应用程序时,我设置了System.Threading.Thread.CurrentPrincial。但是在初始化应用程序并且我想要访问此Principal之后,CurrentPrincipal再次包含默认的GenericPrincipal。

任何人都知道为什么我会这样做?以及如何在初始化应用程序后设置Principal以便访问它。

以下示例演示了行为:

MainWindow.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>

MainWindow.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属性。

1 个答案:

答案 0 :(得分:4)

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

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