c# - 如何实现 VaryByCustom 缓存?

标签 c# asp.net asp.net-mvc caching varybyparam

我正在尝试实现根据主机缓存某些页面的功能。这是因为我可以拥有一个页面的多个版本,这些版本具有相同的参数,并且请求方面的唯一区别是所请求的主机。

例如,这两个 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/

相关文章:

C# 读取 CSV 文件

c# - 将枚举作为字符串存储在数据库中

asp.net - 我需要在 ASP.NET 中取消注册事件吗

asp.net-mvc - 将下拉列表的选定值从 View 传递到 mvc3 中的 Controller ?

c# - 最有效(阅读时间)的字符串搜索方法是什么? (C#)

asp.net 管理多个 web.config 文件

asp.net - 如何在Docker dotnet框架镜像上使用dotnet核心

css - 如何仅覆盖页面上某个部分的标签样式?

asp.net-mvc - 手动触发万无一失的验证

c# - Mvc6 路由(RoutePrefix 和 AreaPrefix)