我想在项目中创建一个沙箱,所以我写了一些测试代码。
但是我似乎很难创建具有特殊权限限制的AppDomain。
这是我的代码,是否有人可以帮助我?
public class HomeController : Controller
{
[Serializable]
public class Person
{
public string Name { get; set; }
}
public ActionResult Index()
{
var appDomain = CreateAppDomain();
using (var service = new IsolatedTemplateService(() => appDomain))
{
// string template = @"<div>Hello @Model.Name</div>";
string template = @"<div>Hello @Model.Name @{ System.IO.File.CreateText(@""c:\\work\\c.txt"");}</div>";
var model = new Person { Name = "Matt" };
string result = service.Parse(template, model, null, null);
Response.Write(result);
}
return View();
}
private AppDomain CreateAppDomain()
{
var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
permissionSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
var assemblies = AppDomain.CurrentDomain.GetAssemblies()
.First(x => x.GetName().Name == "RazorEngine")
.Evidence.GetHostEvidence<StrongName>();
return AppDomain.CreateDomain("RazorTestHost", AppDomain.CurrentDomain.Evidence,
AppDomain.CurrentDomain.SetupInformation, permissionSet, assemblies);
}
}