Dot-Net
檢測信任級別
.NET 應用程序如何檢測其執行所在的信任級別?
具體來說,我想要一種方法來做類似的事情
if (RUNNING IN GREATER THAN MEDIUM TRUST) { // set private fields & properties using reflection }我目前的解決方案是使用
public static class CodeAccessSecurityTool { private static volatile bool _unrestrictedFeatureSet = false; private static volatile bool _determinedUnrestrictedFeatureSet = false; private static readonly object _threadLock = new object(); public static bool HasUnrestrictedFeatureSet { get { if (!_determinedUnrestrictedFeatureSet) lock (_threadLock) { if (!_determinedUnrestrictedFeatureSet) { try { // See if we're running in full trust new PermissionSet(PermissionState.Unrestricted).Demand(); _unrestrictedFeatureSet = true; } catch (SecurityException) { _unrestrictedFeatureSet = false; } _determinedUnrestrictedFeatureSet = true; } } return _unrestrictedFeatureSet; } } }但是,這有點駭人聽聞。
也許這會有所幫助:
ActivationContext ac = AppDomain.CurrentDomain.ActivationContext; ApplicationIdentity ai = ac.Identity; var applicationTrust = new System.Security.Policy.ApplicationTrust(ai); var isUnrestricted = applicationTrust.DefaultGrantSet.PermissionSet.IsUnrestricted();或者
AppDomain.CurrentDomain.ApplicationTrust .DefaultGrantSet.PermissionSet.IsUnrestricted();
從 .NET 4.0 開始,該
AppDomain.IsFullyTrusted屬性可能會有所幫助。如果您希望在目前應用程序域上對此進行測試,請使用:
if (AppDomain.CurrentDomain.IsFullyTrusted) { // ... }