2010-11-18 21 views
0

如何判斷應用程序正在運行的環境?如何判斷你在C#下運行的環境?

也就是說,用戶上下文,系統上下文等...是否有一些我可以運行的代碼告訴? P/Invoke什麼的?

+0

注:我知道,它應該是不言而喻的,但我真的正在尋找一個編程解決方案.. – Grant 2010-11-18 05:39:51

回答

1

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

例如從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

+0

嗨JD,即時獲取空引用o ServiceSecurityContext.Current ..任何想法爲什麼?我從一個控制檯應用程序運行。 – Grant 2010-11-18 05:53:31

+0

@Grant:這意味着您的控制檯應用程序可能以匿名身份運行。你可以通過在運行時檢查'System.ServiceModel.ServiceSecurityContext'類來檢查這個問題 – Darbio 2010-11-18 06:02:00

+0

謝謝JD。我也嘗試從Windows應用程序和它的anonymouse運行。這是什麼意思?我目前從Windows 7登錄到Windows域。難道我沒有當前身份? – Grant 2010-11-18 06:10:15

0

你可以檢查

var isAnonymous = ServiceSecurityContext.Anonymous.IsAnonymous; 

避免nullServiceSecurityContext.Current

相關問題