這篇文章將為大家詳細(xì)講解有關(guān)如何使用asp.net mvc動(dòng)態(tài)編譯生成Controller,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
做網(wǎng)站后臺(tái)管理系統(tǒng)的時(shí)候,有時(shí)我們需要根據(jù)用戶(hù)的錄入配置動(dòng)態(tài)生成一些頻道,這些頻道需要用到獨(dú)立的Controller,這時(shí)就需要用到運(yùn)行時(shí)動(dòng)態(tài)編譯了。代碼如下:
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è)頁(yè)面是vs生成的
點(diǎn)擊動(dòng)態(tài)編譯生成TestController
訪問(wèn)TestController
測(cè)試帶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("錯(cuò)誤信息:" + "
"); foreach (CompilerError error in compiler.Errors) { sb.Append(error.ErrorText + "
"); } #endregion return Content(sb.ToString()); } ////// 動(dòng)態(tài)編譯并執(zhí)行代碼 /// /// 代碼 /// 輸出dll的路徑 ///返回輸出內(nèi)容 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,訪問(wèn)TestController會(huì)提示404錯(cuò)誤
然后點(diǎn)擊動(dòng)態(tài)編譯TestController,生成dll到bin目錄。。再點(diǎn)擊訪問(wèn)TestController的時(shí)候,就是可以訪問(wèn)的狀態(tài)了。
這過(guò)程中,mvc應(yīng)用程序會(huì)自動(dòng)重啟的。。因?yàn)槲覀兊呐渲脙H僅是后臺(tái)使用,我覺(jué)得沒(méi)必要再去動(dòng)態(tài)加載dll,讓他自動(dòng)重啟就行了。。不知道這么想對(duì)不對(duì)。。請(qǐng)大手子賜教。。
關(guān)于如何使用asp.net mvc動(dòng)態(tài)編譯生成Controller就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。