我想使用来自我的'沙盒'类工作者的反射,并抓住我无法解释的行为。
问题可以通过PermissionSet.Assert()来解决,但它看起来像脏黑客。
有谁知道为什么代码权限评估在两种情况下都不同?
public static class Security
{
public static void Fail()
{
var name = Guid.NewGuid().ToString();
var appSetup = new AppDomainSetup
{
ApplicationName = name,
ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
};
// add permissions
var permissions = new PermissionSet(PermissionState.None);
permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
var type = typeof(Worker);
// get strong name to add assembly in full-trusted
var sn1 = type.Assembly.Evidence.GetHostEvidence<StrongName>();
var domain = AppDomain.CreateDomain(name, null, appSetup, permissions, sn1);
var worker = (Worker) Activator.CreateInstanceFrom(domain,
type.Assembly.ManifestModule
.FullyQualifiedName,
type.FullName).Unwrap();
try
{
worker.TryReflect();
}
catch (SecurityException ex)
{
Console.WriteLine(ex.ToString());
}
}
private class Worker : MarshalByRefObject
{
public static int Prop1 { get; private set; }
public void TryReflect()
{
var prop = typeof (Worker).GetProperty("Prop1");
// exception is thrown here:
var val = prop.GetValue(null);
}
}
}