【问题标题】:URL rewrite + outputcacheURL重写+输出缓存
【发布时间】:2014-12-22 05:02:07
【问题描述】:

我在使用 outputcache 和 urlrewriting 时遇到了问题。我们有一个将 url (IE http://localhost/about/) 重写为“~/page.aspx”的应用程序。我们根据 URL (/about/) 确定要显示的内容。

现在我们正在尝试将输出缓存添加到该页面:

< %@ outputcache duration="600" location="Server" varybyparam="Custom" varybycustom="RawURL" %>

在 Global.asax 中,我们重写 GetVaryByCustomString,如下所示:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom == "RawUrl")
    {
        return context.Request.RawUrl;
    }
    else
    {
        return string.Empty;
    }
}

但是,当我们发布页面时,我想使缓存无效,以便编辑者直接看到更改。但无论我尝试什么,我似乎都无法使缓存无效。如果我想使“/about/”无效,我想这样做:

HttpResponse.RemoveOutputCacheItem("/about/");

不幸的是,这不起作用。唯一似乎有效的是:

HttpResponse.RemoveOutputCacheItem("/page.aspx");

这会清除我所有页面的缓存,而不仅仅是“/about/”。

有没有办法根据 url 使缓存失效?或者我们应该为每页提供一个缓存键或其他东西,以便能够以编程方式使缓存无效?

提前致谢!

【问题讨论】:

  • 我猜测负责清除缓存的 asp.net 引擎部分不知道您的重写方案,因此您必须使用实际的文件名。
  • 是的。很公平。那么还有其他选择吗?就像使用页面的 id 作为缓存键一样?我看到的大多数重写示例都重写为“page.aspx?id=x”,这不是我们所做的。
  • 我了解您想要做什么,但我非常怀疑是否可行。除非您想自己实现 RemoveOutputCacheItem :) 也许您可以创建一个枚举来将键映射到物理文件。
  • 其实我就是这么做的。它有效:response.AddCacheItemDependency(currentCategoryGuid); 我在“/page.aspx”中执行此操作,其中 currentCategoryGuid 是当前页面的字符串和 guid(即 /about/)。发布时我会这样做:HttpResponse.RemoveOutputCacheItem(currentCategoryGuid); 这会将其从缓存中删除。其实很简单。 :)

标签: c# .net asp.net url-rewriting outputcache


【解决方案1】:

您不需要使缓存无效。您可以告诉服务器不要对某些请求使用缓存。

要在你的页面加载中添加这个

Response.Cache.AddValidationCallback((ValidateCache), Session);

然后添加这个方法来告诉应用程序是否使用当前请求的输出缓存中的内容

    public static void ValidateCache(HttpContext context, Object data, ref HttpValidationStatus status)
    {

        bool isEditor = /*assignment here*/;
        if (!isEditor)
        {
            status = HttpValidationStatus.Valid;
        }
        else
        {
            status = HttpValidationStatus.IgnoreThisRequest;
        }
    }

如果您不希望某个请求被缓存以供其他用户查看,请使用以下内容

 Response.Cache.SetCacheability(HttpCacheability.NoCache);

【讨论】:

  • 这不是一个真正的选择,因为我们通过“/page.aspx”提供大约 10.000 个页面。使用 outputcache 使应用程序变得更快,因此我们希望将它用于所有页面,并在重新发布某些内容时使每个页面的缓存无效/删除。
【解决方案2】:

我已经使用以下链接解决了。 http://www.superstarcoders.com/blogs/posts/making-asp-net-output-cache-work-with-post-back.aspx

基本上在我的用户控件上;

protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (Request.QueryString["url"] == null)
            return;
        string url = "www." + Request.QueryString["url"].ToString().Replace("http://", "").Replace("https://", "").Replace("www.", "").ToLower();


        Response.AddCacheItemDependency(url);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2016-12-16
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多