首页 技术 正文
技术 2022年11月7日
0 收藏 599 点赞 243 浏览 5121 个字

  在大型网站系统中,为了提高系统访问性能,往往会把一些不经常变得内容发布成静态页,比如商城的产品详情页,新闻详情页,这些信息一旦发布后,变化的频率不会很高,如果还采用动态输出的方式进行处理的话,肯定会给服务器造成很大的资源浪费。但是我们又不能针对这些内容都独立制作静态页,所以我们可以在系统中利用伪静态的方式进行处理,至于什么是伪静态,大家可以百度下。我们这里就来介绍一下,在asp.net core mvc中实现伪静态的方式。

  mvc框架中,view代表的是视图,它执行的结果就是最终输出到客户端浏览器的内容,包含html,css,js等。如果我们想实现静态化,我们就需要把view执行的结果保存成一个静态文件,保存到指定的位置上,比如磁盘、分布式缓存等,下次再访问就可以直接读取保存的内容,而不用再执行一次业务逻辑。那asp.net core mvc要实现这样的功能,应该怎么做?答案是使用过滤器,在mvc框架中,提供了多种过滤器类型,这里我们要使用的是动作过滤器,动作过滤器提供了两个时间点:动作执行前,动作执行后。我们可以在动作执行前,先判断是否已经生成了静态页,如果已经生成,直接读取文件内容输出即可,后续的逻辑就执行跳过。如果没有生产,就继续往下走,在动作执行后这个阶段捕获结果,然后把结果生成的静态内容进行保存。

  那我们就来具体的实现代码,首先我们定义一个过滤器类型,我们成为StaticFileHandlerFilterAttribute,这个类派生自框架中提供的ActionFilterAttribute,StaticFileHandlerFilterAttribute重写基类提供的两个方法:OnActionExecuted(动作执行后),OnActionExecuting(动作执行前),具体代码如下:

  

[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中,需要判断下静态内容是否已经生成,如果已经生成直接输出内容,逻辑实现如下:

//按照一定的规则生成静态文件的名称,这里是按照area+"-"+controller+"-"+action+key规则生成
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默认等于id,当然我们可以配置不同的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返回文件内容
ContentResult contentresult = new ContentResult();
contentresult.Content = sr.ReadToEnd();
contentresult.ContentType = "text/html";
context.Result = contentresult;
}
}
}

  

  在OnActionExecuted中我们需要结果动作结果,判断动作结果类型是否是一个ViewResult,如果是通过代码执行这个结果,获取结果输出,按照上面一样的规则,生成静态页,具体实现如下         

  

         //获取结果
         IActionResult actionResult = context.Result;
         //判断结果是否是一个ViewResult
if (actionResult is ViewResult)
{
ViewResult viewResult = actionResult as ViewResult;
//下面的代码就是执行这个ViewResult,并把结果的html内容放到一个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();
//这句一定要调用,否则内容就会是空的
writer.Flush();
}
//按照规则生成静态文件名称
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());
}
}
//输出当前的结果
ContentResult contentresult = new ContentResult();
contentresult.Content = builder.ToString();
contentresult.ContentType = "text/html";
context.Result = contentresult;
}

  上面提到的Key,我们直接增加对应的属性

        public string Key
{
get;set;
}

  这样我们就可以使用这个过滤器了,使用的方法:在控制器或者控制器方法上增加 [StaticFileHandlerFilter]特性,如果想配置不同的Key,可以使用 [StaticFileHandlerFilter(Key=”设置的值”)]

  静态化已经实现了,我们还需要考虑更新的事,如果后台把一篇文章更新了,我们得把静态页也更新下,方案有很多:一种是在后台进行内容更新时,同步把对应的静态页删除即可。我们这里介绍另外一种,定时更新,就是让静态页有一定的有效期,过了这个有效期自动更新。要实现这个逻辑,我们需要在OnActionExecuting方法中获取静态页的创建时间,然后跟当前时间对比,判断是否已过期,如果未过期直接输出内容,如果已过期,继续执行后面的逻辑。具体代码如下:

  

//获取文件信息对象
FileInfo fileInfo=new FileInfo(filePath);
//结算时间间隔,如果小于等于两分钟,就直接输出,当然这里的规则可以改
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;
}
}
}

  生成了静态内容后,就剩下地址规则修改,这个只需要在Startup调用UseMvc时,规则中使用.html结尾的地址即可。

  到此伪静态就实现好了。目前的处理方法,只能在一定程度上能够提高访问性能,但是针对大型的门户系统来说,可能远远不够。按照上面介绍的方式,可以再进行其他功能扩展,比如生成静态页后可以发布到CDN上,也可以发布到单独的一个内容服务器,等等。不管是什么方式,实现思路都是一样的。

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,966
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,487
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,332
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,115
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,748
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,783