C# Thread.CurrentPrincipal被重置为默认的GenericPrincipal
在初始化应用程序期间,我设置了C# Thread.CurrentPrincipal被重置为默认的GenericPrincipal,c#,wpf,claims,current-principal,C#,Wpf,Claims,Current Principal,在初始化应用程序期间,我设置了System.Threading.Thread.CurrentPrincial。但是,在初始化应用程序并希望访问该主体之后,CurrentPrincipal再次包含默认的GenericPrincipal 有人知道我为什么会有这种行为吗?以及如何设置应用程序初始化后访问它的主体 以下示例演示了该行为: MainWindow.xaml: <Window x:Class="PrincipalTest.MainWindow" xmlns="http://sch
System.Threading.Thread.CurrentPrincial
。但是,在初始化应用程序并希望访问该主体之后,CurrentPrincipal再次包含默认的GenericPrincipal
有人知道我为什么会有这种行为吗?以及如何设置应用程序初始化后访问它的主体
以下示例演示了该行为:
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>
在我的实际项目中,我在引导程序中设置了Thread.CurrentPrincipal
属性。您必须使用
在窗口之后,CurrentPrincipal被重置为默认值(GenericPrincipal)。已加载您试图实现什么?用户模拟?在引导程序中,我想用包含用户名的声明设置currentPrinciple。我从登录Gui、ActiveDirectory用户或数据库中检索的用户名。在登录Gui的情况下没有问题,并且CurrentPrincipal没有重置为GenericPrincipal,为了覆盖WPF中的当前主体,您必须使用AppDomain.CurrentDomain.SetThreadPrincipal(new ClaimsPrincipal())@弗拉基米尔贡达雷夫:这很好用。谢谢你的回答。我有同样的问题,我也在使用Caliburn Micro。你知道为什么会这样吗?最后谢谢。你上一句话为我修正了“在Window.load之后”。嘘。我还有一点头发。还要注意,如果您首先调用
Thread.CurrentPrincipal.Identity
,然后调用AppDomain.CurrentDomain.SetThreadPrincipal()
,那么它也不会工作AppDomain.CurrentDomain.SetThreadPrincipal()
应该始终是第一条语句。
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
}
}
}