Êýøèðîâàíèå è ñæàòèå äàííûõ (gzip) â ASP.NET MVCÈñòî÷íèê: progblog
Êýøèðîâàíèÿ ÿâëÿåòñÿ íåîòúåìëèìîé ÷àñòüþ ëþáîãî êðóïíîãî ñàéòà. Ïîñìîòðèì êàê íà ïðàêòèêå ðåàëèçóåòñÿ êýøèðîâàíèå â ASP.NET MVC. Ñîçäàäèì ñëåäóþùèé ActionFilter:
using System; using System.Web; using System.Web.Mvc; public class CacheFilterAttribute : ActionFilterAttribute { /// <summary> /// Gets or sets the cache duration in seconds. The default is 10 seconds. /// </summary> /// <value>The cache duration in seconds.</value> public int Duration { get; set; } public CacheFilterAttribute() { Duration = 10; } public override void OnActionExecuted(FilterExecutedContext filterContext) { if (Duration <= 0) return; HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache; TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration); cache.SetCacheability(HttpCacheability.Public); cache.SetExpires(DateTime.Now.Add(cacheDuration)); cache.SetMaxAge(cacheDuration); cache.AppendCacheExtension("must-revalidate, proxy-revalidate"); } } Ïðèìåíÿåòñÿ òàêîé ActionFilter î÷åíü ïðîñòî:
[CacheFilter(Duration = 60, Order = 2)] [OutputCache(Duration = 60, VaryByParam = "None", Order = 1)] public ActionResult Index(string alias) Òåïåðü ðåçóëüòàò Index áóäåò çàêýøèðîâàí íà 60 ñåêóíä. OutputCache îòâå÷àåò çà êýøèðîâàíèå ðåçóëüòàòà, à CacheFilter çà çàãîëîâêè âîçâðàùàåìûå ñåðâåðîì. Äëÿ ñæàòèÿ äàííûõ ìåòîäîì gzip, ïîäîéäåò ñëåäóþùèé ActionFilter:
using System.Web; using System.Web.Mvc; public class CompressFilter : ActionFilterAttribute { public override void OnActionExecuting(FilterExecutingContext filterContext) { HttpRequestBase request = filterContext.HttpContext.Request; string acceptEncoding = request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(acceptEncoding)) return; acceptEncoding = acceptEncoding.ToUpperInvariant(); HttpResponseBase response = filterContext.HttpContext.Response; if (acceptEncoding.Contains("GZIP")) { response.AppendHeader("Content-encoding", "gzip"); response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); } else if (acceptEncoding.Contains("DEFLATE")) { response.AppendHeader("Content-encoding", "deflate"); response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); } } } Ïðèìåíÿåòñÿ ñëåäóþùèì îáðàçîì:
[CompressFilter(Order = 3)] [CacheFilter(Duration = 60, Order = 2)] [OutputCache(Duration = 60, VaryByParam = "None", Order = 1)] public ActionResult Index(string alias) Order - ïîðÿäîê ñëåäîâàíèÿ àòòðèáóòîâ. Â ðåçóëüòàòå - îòâåò ñåðâåðà, ñ êýøèðîâàíèåì ("Cache-control: public, must-relative, proxy-revalidate, max-age=30") è ñæàòèåì ("Content-Encoding: gzip"):
|