[英]How to store ASP.NET masterpage data in application cache for set duration
我一直在阅读“ ASP.NET-MVC教程 ”,以了解如何在ASP.NET MVC应用程序中为“母版”视图生成数据。 它提出了使用“基本控制器”并在其构造函数中生成数据的模式。
我的问题是我希望将应用程序数据存储在应用程序缓存中,而不是在viewdata字典中。 应用程序高速缓存在以后的控制器构造函数中不存在,如何在应用程序高速缓存中存储母版页视图的数据?
弄清楚了。 好吧....一个可行的版本。 当ControllerActionInvoker的'InvokeAction'方法激发时,我需要将应用数据添加到缓存中。 为此,我必须创建一个新的ActionInvoker,如下所示。
public class ContextActionInvoker : ControllerActionInvoker
{
public const string testMessageCacheAndViewDataKey = "TESTMESSAGE";
private const int testListLifetimeInMinutes = 10;
public ContextActionInvoker(ControllerContext controllerContext) : base() { }
public override bool InvokeAction(ControllerContext context, string actionName)
{
// Cache a test list if not already done so
var list = context.HttpContext.Cache[testMessageCacheAndViewDataKey];
if (list == null)
{
list = new SelectList(new[] {
new SelectListItem { Text = "Text 10", Value = "10" },
new SelectListItem { Text = "Text 15", Value = "15", Selected = true },
new SelectListItem { Text = "Text 25", Value = "25" },
new SelectListItem { Text = "Text 50", Value = "50" },
new SelectListItem { Text = "Text 100", Value = "100" },
new SelectListItem { Text = "Text 1000", Value = "1000" }
}, "Value", "Text");
context.HttpContext.Cache.Insert(testMessageCacheAndViewDataKey, list, null, DateTime.Now.AddMinutes(testListLifetimeInMinutes), TimeSpan.Zero);
}
context.Controller.ViewData[testMessageCacheAndViewDataKey] = list;
return base.InvokeAction(context, actionName);
}
}
完成此操作后,我需要创建一个自定义controllerfactory,以确保调用了正确的ActionInvoker方法。 我这样做是...
public class ContextControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
IController controller = base.GetControllerInstance(requestContext, controllerType);
Controller contextController = controller as Controller;
if (contextController != null)
{
var context = new ControllerContext(requestContext, contextController);
contextController.ActionInvoker = new ContextActionInvoker(context);
}
return controller;
}
}
然后,我不得不告诉MVC应用程序使用哪个controllerfactory。 我是通过稍微更改Global.asax.cs来实现的...
public class MvcApplication : System.Web.HttpApplication
{
...
protected void Application_Start()
{
...
ControllerBuilder.Current.SetControllerFactory(typeof(ContextControllerFactory));
...
}
...
}
然后,在母版页上,通过执行以下操作,使用了下拉列表HTML帮助器方法:
<%: Html.DropDownList(MVC_MasterPage_data_set_in_cache.Controllers.ContextActionInvoker.testMessageCacheAndViewDataKey) %>
如果您在基本控制器中覆盖Initialize
方法,则可以访问Cache
。 Initialize
将在对控制器中对动作的任何请求执行任何动作之前执行。
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
var list = requestContext.HttpContext.Cache[testMessageCacheAndViewDataKey];
if (list == null) { ... }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.