我的客户希望为用户添加定义小脚本的功能,这些脚本可用于在预先存在的 Web 应用程序中运行各种计算。目前,我们正在探索使用 Microsoft.CodeAnalysis.Scripting.CSharp 中的 CSharpScripts 来动态编译和执行用户函数。
我想要对这些脚本进行沙箱化的能力。具体来说,我想限制脚本可以使用的资源(内存等),以及限制脚本可以访问的库或值(例如,我不希望用户在他们的脚本中调用 Web 服务)。我想避免用户编写的代码会对应用程序的其余部分产生负面影响的情况。
我在下面包含了一些示例代码
private static Script<double> GetCompiledScript(string userFunction)
{
var options = ScriptOptions.Default.AddReferences(References).AddImports(Imports);
var script = CSharpScript.Create<double>(expression, options, typeof(Globals));
script.Compile();
return script;
}
public static String[] Imports => new[]
{
"System",
"System.Linq",
"System.Collections.Generic"
};
public static Assembly[] References => new[]
{
typeof(System.Object).GetTypeInfo().Assembly,
typeof(System.Linq.Enumerable).GetTypeInfo().Assembly,
};
public class Globals
{
public Dictionary<string, double> vars { get; set; }
}