做網(wǎng)站后臺管理系統(tǒng)的時(shí)候,有時(shí)我們需要根據(jù)用戶的錄入配置動(dòng)態(tài)生成一些頻道,這些頻道需要用到獨(dú)立的Controller,這時(shí)就需要用到運(yùn)行時(shí)動(dòng)態(tài)編譯了。代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
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( @" 這個(gè)頁面是vs生成的<br> <a href='/home/creat'>點(diǎn)擊動(dòng)態(tài)編譯生成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( "錯(cuò)誤信息:" + "<br>" ); foreach (CompilerError error in compiler.Errors) { sb.Append(error.ErrorText + "<br>" ); } #endregion return Content(sb.ToString()); } /// <summary> /// 動(dòng)態(tài)編譯并執(zhí)行代碼 /// </summary> /// <param name="csPath">代碼</param> /// <param name="dllName">輸出dll的路徑</param> /// <returns>返回輸出內(nèi)容</returns> private CompilerResults CompilerFromCsPath( string dllName, params string [] csPath) { string binpath = Server.MapPath( "~/bin/" ); CSharpCodeProvider complier = new CSharpCodeProvider(); //設(shè)置編譯參數(shù) 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" ); //是否內(nèi)存中生成輸出 paras.GenerateInMemory = false ; //是否生成可執(zhí)行文件 paras.GenerateExecutable = false ; paras.OutputAssembly = binpath + dllName + ".dll" ; //編譯代碼 CompilerResults result = complier.CompileAssemblyFromFile(paras, csPath); return result; } } } |
流程如下:
mvc啟動(dòng)的時(shí)候,只有HomeController,訪問TestController會(huì)提示404錯(cuò)誤
然后點(diǎn)擊動(dòng)態(tài)編譯TestController,生成dll到bin目錄。。再點(diǎn)擊訪問TestController的時(shí)候,就是可以訪問的狀態(tài)了。
這過程中,mvc應(yīng)用程序會(huì)自動(dòng)重啟的。。因?yàn)槲覀兊呐渲脙H僅是后臺使用,我覺得沒必要再去動(dòng)態(tài)加載dll,讓他自動(dòng)重啟就行了。。不知道這么想對不對。。請大手子賜教。。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。