-
Notifications
You must be signed in to change notification settings - Fork 1
/
CacheableMediaRequestHandler.cs
68 lines (57 loc) · 2.13 KB
/
CacheableMediaRequestHandler.cs
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using Sitecore.Analytics.Media;
namespace CacheableMediaRequest
{
public class CacheableMediaRequestHandler : Sitecore.Resources.Media.MediaRequestHandler
{
private static readonly object cacheLock = new object();
public override void ProcessRequest(HttpContext context)
{
base.ProcessRequest(context);
if (context.Response.StatusCode != 200)
{
return;
}
string key = context.Request.Url.OriginalString;
if (context.Cache[key] != null)
{
return;
}
MediaRequestTrackingInformation info = new MediaRequestTrackingInformation(this.GetMediaRequest(context.Request));
if (info.IsTrackedRequest())
{
return;
}
ResponseFilterStream filter = new ResponseFilterStream(context.Response.Filter);
filter.TransformStream += stream => CachingFilter(stream, context, key);
context.Response.Filter = filter;
}
private static MemoryStream CachingFilter(MemoryStream ms, HttpContext context, string key)
{
byte[] buffer = ms.ToArray();
if (buffer.LongLength > 2000000)
{
return ms;
}
lock (cacheLock)
{
context.Cache.Insert(key, new CacheableMedia
{
Cache = context.Response.Cache,
Output = buffer,
Headers = context.Response.Headers,
StatusCode = context.Response.StatusCode,
ContentType = context.Response.ContentType,
ContentEncoding = context.Response.ContentEncoding,
HeaderEncoding = context.Response.HeaderEncoding,
Charset = context.Response.Charset,
ContentLength = buffer.Length,
}, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10));
}
return ms;
}
}
}