作者:手机用户2502890731 | 来源:互联网 | 2021-09-26 07:08
本篇文章主要介绍了asp.net mvc 动态编译生成Controller的方法,具有一定的参考价值,有兴趣的可以了解一下
做网站后台管理系统的时候,有时我们需要根据用户的录入配置动态生成一些频道,这些频道需要用到独立的Controller,这时就需要用到运行时动态编译了。代码如下:
using System.Web.Mvc;
using System.CodeDom.Compiler;
using System.Text;
using Microsoft.CSharp;
namespace DynamicCompiler.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ContentResult Index()
{
return Content(@"
这个页面是vs生成的
点击动态编译生成TestController
访问TestController
测试带View的Action
");
}
public ContentResult Creat()
{
string cspath = Server.MapPath("~/TestController.cs");
var compiler = CompilerFromCsPath("TestController", cspath); //编译
#region 输出编译信息
StringBuilder sb = new StringBuilder();
sb.Append("cs文件路径:" + cspath);
sb.Append("编译信息:" + "
");
foreach (string output in compiler.Output)
{
sb.Append(output + "
");
}
sb.Append("错误信息:" + "
");
foreach (CompilerError error in compiler.Errors)
{
sb.Append(error.ErrorText + "
");
}
#endregion
return Content(sb.ToString());
}
///
/// 动态编译并执行代码
///
/// 代码
/// 输出dll的路径
/// 返回输出内容
private CompilerResults CompilerFromCsPath(string dllName, params string[] csPath)
{
string binpath = Server.MapPath("~/bin/");
CSharpCodeProvider complier = new CSharpCodeProvider();
//设置编译参数
CompilerParameters paras = new CompilerParameters();
//引入第三方dll
paras.ReferencedAssemblies.Add("System.dll");
paras.ReferencedAssemblies.Add("System.linq.dll");
paras.ReferencedAssemblies.Add("System.Web.dll");
paras.ReferencedAssemblies.Add(binpath + "System.Web.Mvc.dll");
//是否内存中生成输出
paras.GenerateInMemory = false;
//是否生成可执行文件
paras.GenerateExecutable = false;
paras.OutputAssembly = binpath + dllName + ".dll";
//编译代码
CompilerResults result = complier.CompileAssemblyFromFile(paras, csPath);
return result;
}
}
}
流程如下:
这过程中,mvc应用程序会自动重启的。。因为我们的配置仅仅是后台使用,我觉得没必要再去动态加载dll,让他自动重启就行了。。不知道这么想对不对。。请大手子赐教。。
以上就是asp.net mvc如何动态编译生成Controller的方法示例详解的详细内容,更多请关注其它相关文章!