实现asp.net mvc页面二级缓存,提高访问性能
实现的mvc二级缓存的类
//Asp.Net MVC视图页面二级缓存 public class TwoLevelViewCache : IViewLocationCache { private readonly static object SKey = new object(); private readonly IViewLocationCache _cache; public TwoLevelViewCache(IViewLocationCache cache) { _cache = cache; } private static IDictionary<string, string> GetRequestCache(HttpContextBase httpContext) { var d = httpContext.Items[SKey] as IDictionary<string, string>; if (d == null) { d = new Dictionary<string, string>(); httpContext.Items[SKey] = d; } return d; } public string GetViewLocation(HttpContextBase httpContext, string key) { var d = GetRequestCache(httpContext); string location; if (!d.TryGetValue(key, out location)) { location = _cache.GetViewLocation(httpContext, key); d[key] = location; } return location; } public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath) { _cache.InsertViewLocation(httpContext, key, virtualPath); } }
在Global.asax.cs类中Application_Start()方法调用缓存方法,实现二级页面缓存
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ////其余省略 ViewEngines.Engines.Clear();//清除aspx和razor模式,阻断查找两种页面模式所消耗的时间 var ve = new RazorViewEngine(); ve.ViewLocationCache = new TwoLevelViewCache(ve.ViewLocationCache);//创建二级页面缓存,提高性能 ViewEngines.Engines.Add(ve); } }