在 ASP.NET 应用程序中,我想创建一个AppDomain,其中将运行不受信任的代码。但是,在初始化和解包程序集加载程序时,会引发有关我未传入的类型的异常。它是来自网络请求(HttpContext.Current.User
(的当前用户,我认为这是通过LocalCallContext提供的。我不希望当前用户可用于不受信任的代码,实际上我希望不受信任的代码根本没有上下文。所以我想我能够传入一个明确的 CallContext,但似乎没有这样的事情。我将如何实现这一目标?
不受信任的代码是用户提供的 Razor 模板,将通过 RazorEngine 执行。
Evidence evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
PermissionSet permissionSet = SecurityManager.GetStandardSandbox(evidence);
FileIOPermission permission = new FileIOPermission(PermissionState.None);
FileIOPermissionAccess access = FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery;
permission.AddPathList(access, typeof(AssemblyLoader).Assembly.Location);
permissionSet.AddPermission(permission);
// We have to load ourself with full trust
StrongName loaderAssembly = typeof(AssemblyLoader).Assembly.Evidence.GetHostEvidence<StrongName>();
StrongName razorEngineAssembly = typeof(RazorEngineService).Assembly.Evidence.GetHostEvidence<StrongName>();
StrongName razorAssembly = typeof(RazorTemplateEngine).Assembly.Evidence.GetHostEvidence<StrongName>();
AppDomainSetup appDomainSetup = new AppDomainSetup
{
ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
};
AppDomain sandBoxDomain = AppDomain.CreateDomain("Razor Template Sandbox", null, appDomainSetup, permissionSet, loaderAssembly, razorEngineAssembly, razorAssembly);
AssemblyLoader loader = (AssemblyLoader)sandBoxDomain.CreateInstanceFromAndUnwrap(typeof(AssemblyLoader).Assembly.Location, typeof(AssemblyLoader).FullName);
最后一行抛出此异常,UnrelatedAssembly.SomeType
是我的HttpContext.Current.User
类型:
System.Runtime.Serialization.SerializationException: 'Type is not resolved for member 'UnrelatedAssembly.SomeType,UnrelatedAssembly, Version=1.9.0.0, Culture=neutral, PublicKeyToken=null'.'
我通过抑制执行上下文的流并从单独的线程运行目标应用程序域中的所有代码来解决此问题的部分内容。这看起来像这样:
var flow = ExecutionContext.SuppressFlow();
try
{
return Task.Factory.StartNew(() =>
{
Thread.CurrentPrincipal = null;
// setup app domain / run code in other app domain here
return ....;
}).Result;
}
finally
{
flow.Undo();
}