using
System.Web.Mvc;
using
System.CodeDom.Compiler;
using
System.Text;
using
Microsoft.CSharp;
namespace
DynamicCompiler.Controllers
{
public
class
HomeController : Controller
{
public
ContentResult Index()
{
return
Content(
@"
这个页面是vs生成的<br>
<a href='/home/creat'>点击动态编译生成TestController</a><br>
<a href='/Test/'>访问TestController</a><br>
<a href='/Test/WithView'>测试带View的Action</a>
"
);
}
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(
"编译信息:"
+
"<br>"
);
foreach
(
string
output
in
compiler.Output)
{
sb.Append(output +
"<br>"
);
}
sb.Append(
"错误信息:"
+
"<br>"
);
foreach
(CompilerError error
in
compiler.Errors)
{
sb.Append(error.ErrorText +
"<br>"
);
}
#endregion
return
Content(sb.ToString());
}
/// <summary>
/// 动态编译并执行代码
/// </summary>
/// <param name="csPath">代码</param>
/// <param name="dllName">输出dll的路径</param>
/// <returns>返回输出内容</returns>
private
CompilerResults CompilerFromCsPath(
string
dllName,
params
string
[] csPath)
{
string
binpath = Server.MapPath(
"~/bin/"
);
CSharpCodeProvider complier =
new
CSharpCodeProvider();
CompilerParameters paras =
new
CompilerParameters();
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;
}
}
}