非会话用户的输出缓存代码

时间:2016-07-27 04:49:20

标签: c# asp.net c#-4.0 outputcache

如果Session [“user”]为null,我可以在代码后面检测到的页面中进行输出缓存,如果尚未缓存(输出缓存未过期),则将页面缓存5分钟Session [“user”] == null。

我不想使用自定义输出缓存,因为它也会为登录用户缓存。这样,只有匿名访问者才会看到缓存,页面和登录用户将获得非缓存的

我这样做是因为当用户登录时,我的某些页面看起来有所不同。我希望抓取工具和常规访问者看到原始页面,而不是从错误触发缓存的用户那里获取私有数据。

如何在C#后面的代码中执行此操作?

1 个答案:

答案 0 :(得分:1)

您应该可以创建自定义OutputCacheProvider

在你的global.asax中:

    public override string GetOutputCacheProviderName(HttpContext context)
    {
        bool isInSession = true; // Determine here.
        if (isInSession)
        {
            return "CustomProvider";
        }

        // Or by page:
        if (context.Request.Path.EndsWith("MyPage.aspx"))
        {
            return "SomeOtherProvider";
        }

        return base.GetOutputCacheProviderName(context);
    }

然后创建您的提供者:

public class SessionBasedCacheProvider : OutputCacheProvider
{
    public override object Get(string key)
    {
        return null; // Do not cache.
    }

    public override object Add(string key, object entry, DateTime utcExpiry)
    {
        // Basically let it "fall through" since we don't want any caching.
        return entry;
    }

    public override void Set(string key, object entry, DateTime utcExpiry)
    {
        // Basically let it "fall through" since we don't want any caching.            
    }

    public override void Remove(string key)
    {
        // Basically let it "fall through" since we don't want any caching.
    }
}

Set返回null,您将不会缓存这些项目。

  

标识缓存中指定条目的键值,或   如果指定的条目不在缓存中,则返回null。

将您的提供商添加到配置中:

  <system.web>
    <caching>
      <outputCache defaultProvider="AspNetInternalProvider">
        <providers>
          <clear/>
          <add name="CustomProvider" type="YourNamespace.SessionBasedCacheProvider, YourNamespace, Version=1.0.0.0, Culture=neutral"/>
        </providers>
      </outputCache>
    </caching>
</web>

要启用它,您应该可以使用。只需将其设置为ASPX页面的顶部即可。请注意Location属性,具体取决于您希望其缓存的位置。

<%@ OutputCache Duration="60" VaryByParam="None" Location="Server"  %>

https://msdn.microsoft.com/en-us/library/hdxfb6cy(v=vs.85).aspx

https://msdn.microsoft.com/en-us/magazine/gg650661.aspx

或者,您始终可以使用相同的CacheProvider,并让它确定是否应该缓存该项目。

public class CustomOutputCacheProvider : OutputCacheProvider
{
    public override object Add(string key, object entry, DateTime utcExpiry)
    {
        // Determine if in session.
        bool isInSession = true;
        if (isInSession)
        {
            return null;
        }

        // Do the same custom caching as you did in your 
        // CustomMemoryCache object
        var result = HttpContext.Current.Cache.Get(key);

        if (result != null)
        {
            return result;
        }

        HttpContext.Current.Cache.Add(key, entry, null, utcExpiry,
            System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);

        return entry;
    }

    public override object Get(string key)
    {
        return HttpContext.Current.Cache.Get(key);
    }

    public override void Remove(string key)
    {
        HttpContext.Current.Cache.Remove(key);
    }

    public override void Set(string key, object entry, DateTime utcExpiry)
    {
        HttpContext.Current.Cache.Add(key, entry, null, utcExpiry,
            System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
    }
}

来自http://www.haneycodes.net/custom-output-caching-with-mvc3-and-net-4-0-done-right/的代码

注意,我没有使用Session 对此进行测试,但理论上它应该可行。但我建议你在释放之前先测试它。缓存总是比人们想象的要困难得多...... :(

更新:由于会话不可用,您应该可以使用Cookie。

protected void Session_Start(object sender, EventArgs e)
{
    Response.Cookies.Add(new HttpCookie("SessionCookie", "some_value"));
}

public override string GetOutputCacheProviderName(HttpContext context)
{
    bool isInSession = true; // Determine here.

    if (context.Request.Cookies["SessionCookie"] != null)
    {
        // Use your CustomProvider
    }

    if (isInSession)
    {
        return "CustomProvider";
    }

    // Or by page:
    if (context.Request.Path.EndsWith("MyPage.aspx"))
    {
        return "SomeOtherProvider";
    }

    return base.GetOutputCacheProviderName(context);
}

请记住删除cookie,或以某种方式处理它。