【问题标题】:How to use OutputCache for a specific argument only?如何仅将 OutputCache 用于特定参数?
【发布时间】:2013-09-27 15:23:28
【问题描述】:

我有这个 OutputCache 的例子。 我的问题是我希望仅当[id] 等于NULL 时才缓存页面。在所有其他情况下,我根本不想拥有缓存。

我的控制器:

[OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
public ActionResult Details(int id)
{}

路由配置:

routes.MapRoute(
    name: "edit",
    url: "edit/{id}",
    defaults: new {
        controller = "asd",
        action = "Details",
        id = UrlParameter.Optional
    }
);

【问题讨论】:

    标签: asp.net asp.net-mvc outputcache


    【解决方案1】:

    您可以指定(并实现)OutputCacheAttributeVaryByCustom 参数:

    MyController.cs

    [OutputCache(Duration = int.MaxValue, VaryByCustom = "idIsNull")]
    public ActionResult Details(int id)
    {
    }
    

    Global.asax.cs

    public override string GetVaryByCustomString(HttpContext context, string arg)
    {
        if (arg.ToLower() == "idisnull")
        {
            return string.IsNullOrWhiteSpace(Request.QueryString["id"])
                ? string.Empty
                // unique key means it won't have a consistent value to use
                // as a cache lookup
                : ((new DateTime(1970, 1, 1) - DateTime.Now).TotalMilliseconds).ToString();
        }
    }
    

    【讨论】:

    • 谢谢,但 [id] 不是查询字符串。路由详情见编辑
    • @user1615362:我没有看到它在路由url中定义,所以有什么问题?
    • This IsNullOrWhiteSpace(Request.QueryString["id"]) 将永远为真。
    • 根本没有 QueryStiring 参数,我使用的是 RESTful URL,而 [id] 是一个 url 段。
    • @user1615362:再一次......不是根据你的路线。我在该路由中看不到{id} anywhere,因此它要么是 POST 值(在这种情况下应使用 Request.Form)或 GET 变量(坚持使用 Request.QueryString)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2018-08-01
    • 2012-03-08
    相关资源
    最近更新 更多