使用Dotnet-Script 执行一个外部代码

237 237
dotnet-script
Jordan
Jordan 2024-10-21 15:01:25

安装

使用nuget 安装 dotnet-script

使用

        public IActionResult Index()
        {
        // 代码文件
            String scriptPath = @"d:\\dotnet-script\\1.csx";
            using var scriptStream = System.IO.File.OpenRead(scriptPath);
            //定义编译器
            var compiler = new ScriptCompiler(LogFactory, true);
            var runner = new ScriptRunner(compiler, LogFactory, ScriptConsole.Default);
            var sourceText = SourceText.From(scriptStream);
            var context = new ScriptContext(sourceText, Directory.GetCurrentDirectory(), null, null, OptimizationLevel.Release, ScriptMode.Eval);

            var result = runner.Execute<String>(context).GetAwaiter().GetResult();

            Dotnet.Script.DependencyModel.Logging.Logger LogFactory(Type type)
            {
                return (level, message, exception) =>
                {
                    Console.WriteLine($"{level} {message} {exception}");
                };
            }


            return Content("");
        }
回帖
  • 消灭零回复
作者信息
相关文章