缓存对象不会过期ASP Net C#

时间:2014-10-28 13:07:51

标签: c# asp.net caching webforms

我正在为我的网络表单应用程序开发一个缓存功能。我想跟踪用户输入用户名(相同或不同)的次数,以阻止该IP。

我使用1分钟的绝对过期时间,以便缓存对象在创建1分钟后到期,无论上次访问如何。

但是,当我运行应用程序(使用visual studio开发服务器)时,除非重建项目,否则缓存不会过期。

我在线搜索并找到了一些解决方案,例如将滑动过期设置为NoSlidingExpiration,并使用自定义计数器类来存储数据。

我还找到了一个使用system.web标记内的web.config缓存元素的解决方案:

<caching>
  <cache disableExpiration="false"/>
</caching>

缓存仍未过期。任何帮助都会很棒。这是我正在使用的代码。

private int CacheCheck()
{
    // Create the keys used and retrive the values from the cahce
    IncrementingCacheObject cacheUsername = Cache[KeyUsername] as IncrementingCacheObject;
    IncrementingCacheObject cacheDiffAttempts = Cache[KeyDiffAttempts] as IncrementingCacheObject;
    IncrementingCacheObject cacheSameAttempts = Cache[KeySameAttempts] as IncrementingCacheObject;

    // Check if the username exists in cache
    if (cacheUsername != null)
    {
        if (cacheUsername.Username.Equals(this.txtUserName.Text, StringComparison.InvariantCultureIgnoreCase))
        {
            if (cacheSameAttempts != null)
            {
                cacheSameAttempts.Count++;
                this.Cache[KeySameAttempts] = cacheSameAttempts;
            }
            else
            {
                cacheSameAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
                Cache.Insert(KeySameAttempts, cacheSameAttempts, null, cacheSameAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration);
            }
        }
        else
        {
            if (cacheDiffAttempts != null)
            {
                cacheDiffAttempts.Count++;
                this.Cache[KeyDiffAttempts] = cacheDiffAttempts;
            }
            else
            {
                cacheDiffAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
                Cache.Insert(KeyDiffAttempts, cacheDiffAttempts, null, cacheDiffAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration);
            }
        }

        // Set the last used username value in the Cache to the value in the text box
        cacheUsername.Username = this.txtUserName.Text;
        this.Cache[KeyUsername] = cacheUsername;
    }
    else
    {
        cacheUsername = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
        cacheDiffAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
        cacheSameAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
        Cache.Insert(KeyUsername, cacheUsername, null, cacheUsername.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration);
        Cache.Insert(KeySameAttempts, cacheSameAttempts, null, cacheSameAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration);
        Cache.Insert(KeyDiffAttempts, cacheDiffAttempts, null, cacheDiffAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration);
    }

    cacheUsername = Cache[KeyUsername] as IncrementingCacheObject;
    cacheDiffAttempts = Cache[KeyDiffAttempts] as IncrementingCacheObject;
    cacheSameAttempts = Cache[KeySameAttempts] as IncrementingCacheObject;
    // Check whether any log in attempts have surpassed the threshold and return a value to indicate what kind of log in was detected
    if (cacheDiffAttempts != null && cacheDiffAttempts.Count >= MaxLogAttemptsBeforeBan)
    {
        return 0;
    }

    if (cacheSameAttempts != null && cacheSameAttempts.Count >= MaxLogAttemptsBeforeBan)
    {
        return 1;
    }

    return -1;
}

    /// <summary>
    /// This will reset the cache to blank/starting values.
    /// </summary>
    private void ResetCache()
    {
        Cache.Remove(KeyUsername);
        Cache.Remove(KeySameAttempts);
        Cache.Remove(KeyDiffAttempts);
    }

    // Class used to store objects in the cache
    private class IncrementingCacheObject
    {
        public string Username;
        public int Count;
        public DateTime ExpireDate;
    }

当用户成功登录时,在重定向页面之前,它会调用ResetCache()方法。

2 个答案:

答案 0 :(得分:0)

不要使用DateTime.UtcNowCache要求绝对到期时间表示为当地时间。使用DateTime.Now.AddMinutes

答案 1 :(得分:0)

我想出了我遇到的问题。

我在网上找到了这个解决方案:

Stackoverflow Questions

我需要更改一些代码才能正常工作。我不得不删除任何直接分配给Cache并使用insert方法。这是新代码。另外,更改为使用HttpContect.Current.Cache

private int CacheCheck()
{
    // Create the keys used and retrive the values from the cahce
    IncrementingCacheObject cacheUsername = Cache[KeyUsername] as IncrementingCacheObject;
    IncrementingCacheObject cacheDiffAttempts = Cache[KeyDiffAttempts] as IncrementingCacheObject;
    IncrementingCacheObject cacheSameAttempts = Cache[KeySameAttempts] as IncrementingCacheObject;

    // Check if the username exists in cache
    if (cacheUsername != null)
    {
        if (cacheUsername.Username.Equals(this.txtUserName.Text, StringComparison.InvariantCultureIgnoreCase))
        {
            if (cacheSameAttempts != null)
            {
                cacheSameAttempts.Count++;
            }
            else
            {
                cacheSameAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
            }

            HttpContext.Current.Cache.Insert(KeySameAttempts, cacheSameAttempts, null, cacheSameAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
        }
        else
        {
            if (cacheDiffAttempts != null)
            {
                cacheDiffAttempts.Count++;
            }
            else
            {
                cacheDiffAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
            }

            HttpContext.Current.Cache.Insert(KeyDiffAttempts, cacheDiffAttempts, null, cacheDiffAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
        }

        // Set the last used username value in the Cache to the value in the text box
        cacheUsername.Username = this.txtUserName.Text;
    }
    else
    {
        cacheUsername = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
        cacheDiffAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
        cacheSameAttempts = new IncrementingCacheObject { Count = 0, ExpireDate = DateTime.UtcNow.AddMinutes(1), Username = this.txtUserName.Text };
        HttpContext.Current.Cache.Insert(KeySameAttempts, cacheSameAttempts, null, cacheSameAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
        HttpContext.Current.Cache.Insert(KeyDiffAttempts, cacheDiffAttempts, null, cacheDiffAttempts.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
    }

    HttpContext.Current.Cache.Insert(KeyUsername, cacheUsername, null, cacheUsername.ExpireDate, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);

    // Check whether any log in attempts have surpassed the threshold and return a value to indicate what kind of log in was detected
    if (cacheDiffAttempts != null && cacheDiffAttempts.Count >= MaxLogAttemptsBeforeBan)
    {
        return 0;
    }

    if (cacheSameAttempts != null && cacheSameAttempts.Count >= MaxLogAttemptsBeforeBan)
    {
        return 1;
    }

    return -1;
}

/// <summary>
/// This will reset the cache to blank/starting values.
/// </summary>
private void ResetCache()
{
    HttpContext.Current.Cache.Remove(KeyUsername);
    HttpContext.Current.Cache.Remove(KeySameAttempts);
    HttpContext.Current.Cache.Remove(KeyDiffAttempts);
}

// Class used to store objects in the cache
private class IncrementingCacheObject
{
    public string Username;
    public int Count;
    public DateTime ExpireDate;
}