我正在尝试实现根据主机缓存某些页面的功能。这是因为我可以拥有一个页面的多个版本,这些版本具有相同的参数,并且请求方面的唯一区别是所请求的主机。
例如,这两个 URL 将请求相同的页面,但它们的样式不同:
http://www.a.com/something/specific
和
http://www.b.com/something/specific
我正在查看此处概述的示例:
http://msdn.microsoft.com/en-us/library/5ecf4420%28v=VS.90%29.aspx
但这对我来说没有意义。
我已将其添加到我的 global.asax 中:
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg == "host")
{
return "host=" + context.Request.Url.Host;
}
return base.GetVaryByCustomString(context, arg);
}
示例说明“要以编程方式设置自定义字符串,请调用 SetVaryByCustom 方法并将要使用的自定义字符串传递给它”,代码类似于以下内容:
Response.Cache.SetVaryByCustom("host");
问题是我不确定该怎么做。我已将上一行添加到 MvcApplication_EndRequest
中,因为它看起来很有意义,但我认为这是不对的,因为当我在 GetVaryByCustomString
中设置断点时,它们永远不会得到命中。
有人可以告诉我我在这里缺少什么吗?或者我是否需要以不同的方式执行此操作?
编辑: RE Darin 在下面的回答,我已经在装饰我的行为了:
[CustomOutputCache(CacheProfile = "FundScreener")] // or similar depending on the action
其中 CustomOutputCacheAttribute
定义为:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomOutputCacheAttribute: OutputCacheAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
AddLabelFilesDependency(filterContext);
base.OnResultExecuted(filterContext);
}
private static void AddLabelFilesDependency(ControllerContext filterContext)
{
IConfigurationManager configurationManager = ObjectFactory.TryGetInstance<IConfigurationManager>();
if (configurationManager == null
|| filterContext == null
|| filterContext.RequestContext == null
|| filterContext.RequestContext.HttpContext == null
|| filterContext.RequestContext.HttpContext.Response == null
)
{
return;
}
string[] files = Directory.GetFiles(configurationManager.LabelsDirectoryPath, "*.xml");
foreach(var file in files)
{
filterContext.RequestContext.HttpContext.Response.AddFileDependency(file);
}
}
}
其中配置文件定义为:
<add name="FundScreener"
location="Server"
enabled="true"
varyByParam="*"
duration="1200"
sqlDependency="mmftms:offline.ScreenerData"/>
我需要更改吗?
最佳答案
您不需要在 MVC 中调用 SetVaryByCustom
。您可以使用 OutputCache
属性。查看following blog post .
关于c# - 如何实现 VaryByCustom 缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5313921/