简体   繁体   English

如何判断在C#中运行什么上下文?

[英]How to tell what context you are running under in C#?

How do I to tell what context an application is running under? 如何判断应用程序在什么环境下运行?

That is, user context, system context, etc... Is there some code I can run to tell? 也就是说,用户上下文,系统上下文等。是否可以运行一些代码来告诉我? P/Invoke or something? P /调用什么?

Look at the .NET class ServiceSecurityContext.Current -> http://msdn.microsoft.com/en-us/library/system.servicemodel.servicesecuritycontext.aspx 查看.NET类ServiceSecurityContext.Current > http://msdn.microsoft.com/zh-cn/library/system.servicemodel.servicesecuritycontext.aspx

Eg The following example from MSDN shows you how to use this class 例如,来自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);
            }
        }
    }
}

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

You could check on 你可以检查一下

var isAnonymous = ServiceSecurityContext.Anonymous.IsAnonymous;

to avoid null on ServiceSecurityContext.Current 避免在ServiceSecurityContext.Current null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM