MVC 静态化的ActionFilter

时间:2023-12-23 20:53:01

在MVC中,需要对某些页面进行静态化,用ActionFilter来做静态化,把页面存到缓存中。如下代码所示,其中Result.RenderString是扩展方法,第一次缓存的时候,Action代码会运行两次,其中一次是RenderString这个方法重复调用Action的Render,待改善

不采用IResultFilter是因为需要跳过Action的执行过程

       /// <summary>
/// 页面缓存
/// </summary>
/// <param name="expiry">缓存过期时间</param>
/// <param name="cacheProvider">缓存器名称</param>
public ResultCachingAttribute(int expiry = 60, string cacheProvider = "default")
{
_timeSpan = TimeSpan.FromSeconds(expiry);
_cacheProvider = cacheProvider;
} public void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
string key = "_page_{0}_{1}_{2}";
string controller = filterContext.RouteData.GetRequiredString("controller");
string action = filterContext.RouteData.GetRequiredString("action"); string strUrl = string.Empty;
if (filterContext.HttpContext.Request != null && filterContext.HttpContext.Request.Url != null)
strUrl = filterContext.HttpContext.Request.Url.Query; _cacheKey = string.Format(key, controller, action, strUrl); cache = CacheManager.GetInstance(_cacheProvider);
string cachedPage = cache.Get<string>(_cacheKey);
if (!string.IsNullOrWhiteSpace(cachedPage))
{
filterContext.Result = new ContentResult()
{
Content = cachedPage
};
}
}
catch (Exception exception)
{
Logger logger = LoggerManager.GetLogger("Common.Filter");
logger.Error(string.Format("CachingResult Error {0},\n{1}", _cacheKey, exception.Message), exception);
}
} public void OnActionExecuted(ActionExecutedContext filterContext)
{
try
{
if (!string.IsNullOrWhiteSpace(_cacheKey))
{
cache = CacheManager.GetInstance(_cacheProvider);
string strResult = filterContext.Result.RenderString(filterContext.Controller.ControllerContext);
cache.Set(_cacheKey, strResult, _timeSpan);
}
}
catch (Exception exception)
{
Logger logger = LoggerManager.GetLogger("Common.Filter");
logger.Error(string.Format("CachingResult Error {0},\n{1}", _cacheKey, exception.Message), exception);
}
}