summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/src/System.Web.Helpers/WebCache.cs
blob: 8189a34538ea5a823360a9bb24e690f4f3656214 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Globalization;
using System.Runtime.Caching;
using Microsoft.Internal.Web.Utils;

namespace System.Web.Helpers
{
    public static class WebCache
    {
        public static void Set(string key, object value, int minutesToCache = 20, bool slidingExpiration = true)
        {
            if (minutesToCache <= 0)
            {
                throw new ArgumentOutOfRangeException("minutesToCache",
                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));
            }
            else if (slidingExpiration && (minutesToCache > 365 * 24 * 60))
            {
                // For sliding expiration policies, MemoryCache has a time limit of 365 days. 
                throw new ArgumentOutOfRangeException("minutesToCache",
                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_LessThanOrEqualTo, 365 * 24 * 60));
            }

            CacheItemPolicy policy = new CacheItemPolicy();
            TimeSpan expireTime = new TimeSpan(0, minutesToCache, 0);

            if (slidingExpiration)
            {
                policy.SlidingExpiration = expireTime;
            }
            else
            {
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesToCache);
            }

            MemoryCache.Default.Set(key, value, policy);
        }

        public static dynamic Get(string key)
        {
            return MemoryCache.Default.Get(key);
        }

        public static dynamic Remove(string key)
        {
            return MemoryCache.Default.Remove(key);
        }
    }
}