Thread.CurrentPrincipal in .NET console application

拜拜、爱过 提交于 2019-12-06 18:06:41

问题


Here is a trivial console application that i run in command prompt:

using System;
using System.Threading;
namespace Test
{
    internal class Runner
    {
        [STAThread]
        static void Main(string[] args)
        {
            Console.WriteLine(Thread.CurrentPrincipal.GetType().Name);
            Console.WriteLine(Thread.CurrentPrincipal.Identity.Name);
        }
    }
}

The output is 'GenericPrincipal' and empty string as identity name. Why the run-time constructs GenericPrincipal instead of WindowsPrincipal? How do i force it to construct WindowsPrincipal from the security token of the starting process (cmd.exe in my case)?


回答1:


You have to tell your app what PrincipalPolicy to use. You would add

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

making your code look like:

using System;
using System.Threading;
using System.Security.Principal;

namespace Test
{
    internal class Runner
    {
        [STAThread]
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            Console.WriteLine(Thread.CurrentPrincipal.GetType().Name);
            Console.WriteLine(Thread.CurrentPrincipal.Identity.Name);
        }
    }
}

See http://msdn.microsoft.com/en-us/library/system.appdomain.setprincipalpolicy.aspx



来源:https://stackoverflow.com/questions/4421971/thread-currentprincipal-in-net-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!