Dav*_*Dev 15 c# asp.net asp.net-mvc caching varybyparam
我正在尝试实现根据主机缓存某些页面的功能.这是因为我可以拥有具有相同参数的页面的多个版本,并且请求方面唯一的区别是正在请求的主机.
因此,例如这两个URL将请求相同的页面,但它们的样式不同:
http://www.a.com/something/specific
Run Code Online (Sandbox Code Playgroud)
和
http://www.b.com/something/specific
Run Code Online (Sandbox Code Playgroud)
我将通过这里概述的示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
并且示例声明"要以编程方式设置自定义字符串,请调用SetVaryByCustom方法并将其传递给要使用的自定义字符串",代码类似于以下内容:
Response.Cache.SetVaryByCustom("host");
Run Code Online (Sandbox Code Playgroud)
问题是我不知道该怎么办.我已经添加了前一行,MvcApplication_EndRequest
因为它似乎有意义,但我不认为这是正确的,因为当我设置断点时,GetVaryByCustomString
它们永远不会被击中.
有人可以告诉我我在这里失踪了吗?或者如果我需要以不同方式做到这一点?
编辑: RE Darin的答案如下,我已经用以下方式装饰我的行为:
[CustomOutputCache(CacheProfile = "FundScreener")] // or similar depending on the action
Run Code Online (Sandbox Code Playgroud)
其中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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
配置文件定义为:
<add name="FundScreener"
location="Server"
enabled="true"
varyByParam="*"
duration="1200"
sqlDependency="mmftms:offline.ScreenerData"/>
Run Code Online (Sandbox Code Playgroud)
我需要更改吗?
你不需要调用SetVaryByCustom
MVC.您可以使用该OutputCache
属性.查看以下博客文章.