如何在C#中告诉你运行的上下文?

时间:2010-11-18 05:36:30

标签: c# windows

如何判断运行应用程序的上下文?

即用户上下文,系统上下文等...是否有一些我可以运行的代码来告诉? P/Invoke还是什么?

2 个答案:

答案 0 :(得分:1)

查看.NET类ServiceSecurityContext.Current - > http://msdn.microsoft.com/en-us/library/system.servicemodel.servicesecuritycontext.aspx

E.g。 MSDN中的以下示例向您展示了如何使用此类

// Run this method from within a method protected by the PrincipalPermissionAttribute
// to see the security context data, including the primary identity.
public void WriteServiceSecurityContextData(string fileName)
{
    using (StreamWriter sw = new StreamWriter(fileName))
    {
        // Write the primary identity and Windows identity. The primary identity is derived from
        // the credentials used to authenticate the user. The Windows identity may be a null string.
        sw.WriteLine("PrimaryIdentity: {0}", ServiceSecurityContext.Current.PrimaryIdentity.Name);
        sw.WriteLine("WindowsIdentity: {0}", ServiceSecurityContext.Current.WindowsIdentity.Name);
        sw.WriteLine();
        // Write the claimsets in the authorization context. By default, there is only one claimset
        // provided by the system. 
        foreach (ClaimSet claimset in ServiceSecurityContext.Current.AuthorizationContext.ClaimSets)
        {
            foreach (Claim claim in claimset)
            {
                // Write out each claim type, claim value, and the right. There are two
                // possible values for the right: "identity" and "possessproperty". 
                sw.WriteLine("Claim Type = {0}", claim.ClaimType);
                sw.WriteLine("\t Resource = {0}", claim.Resource.ToString());
                sw.WriteLine("\t Right = {0}", claim.Right);
            }
        }
    }
}

来源:http://msdn.microsoft.com/en-us/library/aa347790.aspx

答案 1 :(得分:0)

您可以查看

var isAnonymous = ServiceSecurityContext.Anonymous.IsAnonymous;

以避免null

上的ServiceSecurityContext.Current