日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

asp.net core mvc实现伪静态功能

發(fā)布時(shí)間:2023/12/4 asp.net 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 asp.net core mvc实现伪静态功能 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

  在大型網(wǎng)站系統(tǒng)中,為了提高系統(tǒng)訪問性能,往往會(huì)把一些不經(jīng)常變得內(nèi)容發(fā)布成靜態(tài)頁,比如商城的產(chǎn)品詳情頁,新聞詳情頁,這些信息一旦發(fā)布后,變化的頻率不會(huì)很高,如果還采用動(dòng)態(tài)輸出的方式進(jìn)行處理的話,肯定會(huì)給服務(wù)器造成很大的資源浪費(fèi)。但是我們又不能針對(duì)這些內(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é)果保存成一個(gè)靜態(tài)文件,保存到指定的位置上,比如磁盤、分布式緩存等,下次再訪問就可以直接讀取保存的內(nèi)容,而不用再執(zhí)行一次業(yè)務(wù)邏輯。那asp.net core mvc要實(shí)現(xiàn)這樣的功能,應(yīng)該怎么做?答案是使用過濾器,在mvc框架中,提供了多種過濾器類型,這里我們要使用的是動(dòng)作過濾器,動(dòng)作過濾器提供了兩個(gè)時(shí)間點(diǎn):動(dòng)作執(zhí)行前,動(dòng)作執(zhí)行后。我們可以在動(dòng)作執(zhí)行前,先判斷是否已經(jīng)生成了靜態(tài)頁,如果已經(jīng)生成,直接讀取文件內(nèi)容輸出即可,后續(xù)的邏輯就執(zhí)行跳過。如果沒有生產(chǎn),就繼續(xù)往下走,在動(dòng)作執(zhí)行后這個(gè)階段捕獲結(jié)果,然后把結(jié)果生成的靜態(tài)內(nèi)容進(jìn)行保存。

  那我們就來具體的實(shí)現(xiàn)代碼,首先我們定義一個(gè)過濾器類型,我們成為StaticFileHandlerFilterAttribute,這個(gè)類派生自框架中提供的ActionFilterAttribute,StaticFileHandlerFilterAttribute重寫基類提供的兩個(gè)方法:OnActionExecuted(動(dòng)作執(zhí)行后),OnActionExecuting(動(dòng)作執(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é)果動(dòng)作結(jié)果,判斷動(dòng)作結(jié)果類型是否是一個(gè)ViewResult,如果是通過代碼執(zhí)行這個(gè)結(jié)果,獲取結(jié)果輸出,按照上面一樣的規(guī)則,生成靜態(tài)頁,具體實(shí)現(xiàn)如下         



//獲取結(jié)果 IActionResult actionResult = context.Result; ? //判斷結(jié)果是否是一個(gè)ViewResult ??????? if (actionResult is ViewResult) ??????? { ??????????? ViewResult viewResult = actionResult as ViewResult; ??????????? //下面的代碼就是執(zhí)行這個(gè)ViewResult,并把結(jié)果的html內(nèi)容放到一個(gè)StringBuiler對(duì)象中 ??????????? 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)容就會(huì)是空的 ??????????????? 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,我們直接增加對(duì)應(yīng)的屬性


public string Key { ???? get ; set ; }

  這樣我們就可以使用這個(gè)過濾器了,使用的方法:在控制器或者控制器方法上增加?[StaticFileHandlerFilter]特性,如果想配置不同的Key,可以使用?[StaticFileHandlerFilter(Key="設(shè)置的值")]

  靜態(tài)化已經(jīng)實(shí)現(xiàn)了,我們還需要考慮更新的事,如果后臺(tái)把一篇文章更新了,我們得把靜態(tài)頁也更新下,方案有很多:一種是在后臺(tái)進(jìn)行內(nèi)容更新時(shí),同步把對(duì)應(yīng)的靜態(tài)頁刪除即可。我們這里介紹另外一種,定時(shí)更新,就是讓靜態(tài)頁有一定的有效期,過了這個(gè)有效期自動(dòng)更新。要實(shí)現(xiàn)這個(gè)邏輯,我們需要在OnActionExecuting方法中獲取靜態(tài)頁的創(chuàng)建時(shí)間,然后跟當(dāng)前時(shí)間對(duì)比,判斷是否已過期,如果未過期直接輸出內(nèi)容,如果已過期,繼續(xù)執(zhí)行后面的邏輯。具體代碼如下:


//獲取文件信息對(duì)象 FileInfo fileInfo= new FileInfo(filePath); //結(jié)算時(shí)間間隔,如果小于等于兩分鐘,就直接輸出,當(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)好了。目前的處理方法,只能在一定程度上能夠提高訪問性能,但是針對(duì)大型的門戶系統(tǒng)來說,可能遠(yuǎn)遠(yuǎn)不夠。按照上面介紹的方式,可以再進(jìn)行其他功能擴(kuò)展,比如生成靜態(tài)頁后可以發(fā)布到CDN上,也可以發(fā)布到單獨(dú)的一個(gè)內(nèi)容服務(wù)器,等等。不管是什么方式,實(shí)現(xiàn)思路都是一樣的。


總結(jié)

以上是生活随笔為你收集整理的asp.net core mvc实现伪静态功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。