这篇文章将为大家详细讲解有关如何使用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启动的时候,只有HomeController,访问TestController会提示404错误

然后点击动态编译TestController,生成dll到bin目录。。再点击访问TestController的时候,就是可以访问的状态了。


这过程中,mvc应用程序会自动重启的。。因为我们的配置仅仅是后台使用,我觉得没必要再去动态加载dll,让他自动重启就行了。。不知道这么想对不对。。请大手子赐教。。
关于如何使用asp.net mvc动态编译生成Controller就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。