在大型網(wǎng)站系統(tǒng)中,為了提高系統(tǒng)訪問性能,往往會把一些不經(jīng)常變得內(nèi)容發(fā)布成靜態(tài)頁,比如商城的產(chǎn)品詳情頁,新聞詳情頁,這些信息一旦發(fā)布后,變化的頻率不會很高,如果還采用動態(tài)輸出的方式進(jìn)行處理的話,肯定會給服務(wù)器造成很大的資源浪費(fèi)。但是我們又不能針對這些內(nèi)容都獨(dú)立制作靜態(tài)頁,所以我們可以在系統(tǒng)中利用偽靜態(tài)的方式進(jìn)行處理,至于什么是偽靜態(tài),大家可以百度下。我們這里就來介紹一下,在asp.net core mvc中實(shí)現(xiàn)偽靜態(tài)的方式。
mvc框架中,view代表的是視圖,它執(zhí)行的結(jié)果就是最終輸出到客戶端瀏覽器的內(nèi)容,包含html,css,js等。如果我們想實(shí)現(xiàn)靜態(tài)化,我們就需要把view執(zhí)行的結(jié)果保存成一個靜態(tài)文件,保存到指定的位置上,比如磁盤、分布式緩存等,下次再訪問就可以直接讀取保存的內(nèi)容,而不用再執(zhí)行一次業(yè)務(wù)邏輯。那asp.net core mvc要實(shí)現(xiàn)這樣的功能,應(yīng)該怎么做?答案是使用過濾器,在mvc框架中,提供了多種過濾器類型,這里我們要使用的是動作過濾器,動作過濾器提供了兩個時間點(diǎn):動作執(zhí)行前,動作執(zhí)行后。我們可以在動作執(zhí)行前,先判斷是否已經(jīng)生成了靜態(tài)頁,如果已經(jīng)生成,直接讀取文件內(nèi)容輸出即可,后續(xù)的邏輯就執(zhí)行跳過。如果沒有生產(chǎn),就繼續(xù)往下走,在動作執(zhí)行后這個階段捕獲結(jié)果,然后把結(jié)果生成的靜態(tài)內(nèi)容進(jìn)行保存。
那我們就來具體的實(shí)現(xiàn)代碼,首先我們定義一個過濾器類型,我們成為StaticFileHandlerFilterAttribute,這個類派生自框架中提供的ActionFilterAttribute,StaticFileHandlerFilterAttribute重寫基類提供的兩個方法:OnActionExecuted(動作執(zhí)行后),OnActionExecuting(動作執(zhí)行前),具體代碼如下:
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false, Inherited = false)]public class StaticFileHandlerFilterAttribute : ActionFilterAttribute{ public override void OnActionExecuted(ActionExecutedContext context){} public override void OnActionExecuting(ActionExecutingContext context){}}
在OnActionExecuting中,需要判斷下靜態(tài)內(nèi)容是否已經(jīng)生成,如果已經(jīng)生成直接輸出內(nèi)容,邏輯實(shí)現(xiàn)如下:
//按照一定的規(guī)則生成靜態(tài)文件的名稱,這里是按照area+"-"+controller+"-"+action+key規(guī)則生成string controllerName = context.RouteData.Values["controller"].ToString().ToLower();string actionName = context.RouteData.Values["action"].ToString().ToLower();string area = context.RouteData.Values["area"].ToString().ToLower();//這里的Key默認(rèn)等于id,當(dāng)然我們可以配置不同的Key名稱string id = context.RouteData.Values.ContainsKey(Key) ? context.RouteData.Values[Key].ToString() : "";if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(Key)){ id = context.HttpContext.Request.Query[Key];}string filePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", area, controllerName + "-" + actionName + (string.IsNullOrEmpty(id) ? "" : ("-" + id)) + ".html");//判斷文件是否存在if (File.Exists(filePath)){ //如果存在,直接讀取文件 using (FileStream fs = File.Open(filePath, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { //通過contentresult返回文件內(nèi)容 ContentResult contentresult = new ContentResult(); contentresult.Content = sr.ReadToEnd(); contentresult.ContentType = "text/html"; context.Result = contentresult; } }}
在OnActionExecuted中我們需要結(jié)果動作結(jié)果,判斷動作結(jié)果類型是否是一個ViewResult,如果是通過代碼執(zhí)行這個結(jié)果,獲取結(jié)果輸出,按照上面一樣的規(guī)則,生成靜態(tài)頁,具體實(shí)現(xiàn)如下
//獲取結(jié)果IActionResult actionResult = context.Result; //判斷結(jié)果是否是一個ViewResult if (actionResult is ViewResult) { ViewResult viewResult = actionResult as ViewResult; //下面的代碼就是執(zhí)行這個ViewResult,并把結(jié)果的html內(nèi)容放到一個StringBuiler對象中 var services = context.HttpContext.RequestServices; var executor = services.GetRequiredService<ViewResultExecutor>(); var option = services.GetRequiredService<IOptions<MvcViewOptions>>(); var result = executor.FindView(context, viewResult); result.EnsureSuccessful(originalLocations: null); var view = result.View; StringBuilder builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { var viewContext = new ViewContext( context, view, viewResult.ViewData, viewResult.TempData, writer, option.Value.HtmlHelperOptions); view.RenderAsync(viewContext).GetAwaiter().GetResult(); //這句一定要調(diào)用,否則內(nèi)容就會是空的 writer.Flush(); } //按照規(guī)則生成靜態(tài)文件名稱 string area = context.RouteData.Values["area"].ToString().ToLower(); string controllerName = context.RouteData.Values["controller"].ToString().ToLower(); string actionName = context.RouteData.Values["action"].ToString().ToLower(); string id = context.RouteData.Values.ContainsKey(Key) ? context.RouteData.Values[Key].ToString() : ""; if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(Key)) { id = context.HttpContext.Request.Query[Key]; } string devicedir = Path.Combine(AppContext.BaseDirectory, "wwwroot", area); if (!Directory.Exists(devicedir)) { Directory.CreateDirectory(devicedir); } //寫入文件 string filePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", area, controllerName + "-" + actionName + (string.IsNullOrEmpty(id) ? "" : ("-" + id)) + ".html"); using (FileStream fs = File.Open(filePath, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { sw.Write(builder.ToString()); } } //輸出當(dāng)前的結(jié)果 ContentResult contentresult = new ContentResult(); contentresult.Content = builder.ToString(); contentresult.ContentType = "text/html"; context.Result = contentresult; }
上面提到的Key,我們直接增加對應(yīng)的屬性
public string Key{ get;set;}
這樣我們就可以使用這個過濾器了,使用的方法:在控制器或者控制器方法上增加 [StaticFileHandlerFilter]特性,如果想配置不同的Key,可以使用 [StaticFileHandlerFilter(Key="設(shè)置的值")]
靜態(tài)化已經(jīng)實(shí)現(xiàn)了,我們還需要考慮更新的事,如果后臺把一篇文章更新了,我們得把靜態(tài)頁也更新下,方案有很多:一種是在后臺進(jìn)行內(nèi)容更新時,同步把對應(yīng)的靜態(tài)頁刪除即可。我們這里介紹另外一種,定時更新,就是讓靜態(tài)頁有一定的有效期,過了這個有效期自動更新。要實(shí)現(xiàn)這個邏輯,我們需要在OnActionExecuting方法中獲取靜態(tài)頁的創(chuàng)建時間,然后跟當(dāng)前時間對比,判斷是否已過期,如果未過期直接輸出內(nèi)容,如果已過期,繼續(xù)執(zhí)行后面的邏輯。具體代碼如下:
//獲取文件信息對象FileInfo fileInfo=new FileInfo(filePath);//結(jié)算時間間隔,如果小于等于兩分鐘,就直接輸出,當(dāng)然這里的規(guī)則可以改TimeSpan ts = DateTime.Now - fileInfo.CreationTime;if(ts.TotalMinutes<=2){ using (FileStream fs = File.Open(filePath, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { ContentResult contentresult = new ContentResult(); contentresult.Content = sr.ReadToEnd(); contentresult.ContentType = "text/html"; context.Result = contentresult; } }}
到此偽靜態(tài)就實(shí)現(xiàn)好了。目前的處理方法,只能在一定程度上能夠提高訪問性能,但是針對大型的門戶系統(tǒng)來說,可能遠(yuǎn)遠(yuǎn)不夠。按照上面介紹的方式,可以再進(jìn)行其他功能擴(kuò)展,比如生成靜態(tài)頁后可以發(fā)布到CDN上,也可以發(fā)布到單獨(dú)的一個內(nèi)容服務(wù)器,等等。不管是什么方式,實(shí)現(xiàn)思路都是一樣的。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選