我正在尝试在沙盒中运行一段代码。它失败了,问题出在使用缓存的代码部分。
按预期工作的情况:
public void Demo()
{
// Verify that the code is running in a sandbox: the next line is expected to
// fail, since the sandbox doesn't have enough I/O privileges to access H:\.
File.WriteAllText(@"H:\Hello.txt", "Hello");
}
按预期工作,即抛出异常,显示“请求权限 [...] FileIOPermission [...] 失败。”。
当我通过调用数据库替换代码时,再次出现预期结果:应用程序提示没有足够的权限。
如果我添加请求的权限,代码将无一异常(exception)地执行。
失败的情况:
如果我将之前的方法替换为:
public void Demo()
{
Cache cache = HttpRuntime.Cache;
File.WriteAllText(@"H:\Hello.txt", "Hello");
}
它停止工作:抛出的不是提示 I/O 权限不足的预期异常,而是 System.Security.SecurityException
:
That assembly does not allow partially trusted callers.
是否与此问题有关,或者缓存不打算用于完全信任以外的场景?
最佳答案
在以部分信任方式运行的代码中使用缓存的一种可能方法是将缓存对象移出插件。可以使用适配器模式,以便插件仍然能够在缓存中读取和写入数据,同时由调用者在完全信任的上下文中管理缓存。
如果其他人有兴趣,我说明一下the original issue和 a project published on CodePlex 中的解决方案.
关于c# - System.Web.Caching.Cache 是否有望在沙箱中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11182321/