Пример #1
0
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        private void SetHeadersAndCache(string file, HttpContext context)
        {
            //string ext = file.Substring(file.LastIndexOf(".")).ToString().ToLower();

            //TimeSpan maxAge = new TimeSpan(3, 0, 0, 0);

            //context.Response.Cache.SetMaxAge(maxAge);

            //context.Response.AddFileDependency(file);
            //context.Response.Cache.SetCacheability(HttpCacheability.Public);

            //context.Response.Cache.VaryByParams["path"] = true;
            //context.Response.Cache.SetETagFromFileDependencies();
            //context.Response.Cache.SetExpires(DateTime.Now.AddDays(3));
            //context.Response.Expires = 86400000;
            //context.Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            //context.Response.Cache.SetETag(string.Empty);
            //context.Response.Cache.SetLastModifiedFromFileDependencies();

            HttpResponse response = context.Response;

            TimeSpan duration = TimeSpan.FromDays(3);

            HttpCachePolicy cache = response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(duration));
            cache.SetMaxAge(duration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

            FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);

            maxAgeField.SetValue(cache, duration);
        }
        /// <summary>
        /// Sets the output cache parameters and also the client side caching parameters
        /// </summary>
        /// <param name="context"></param>
        private void SetCaching(HttpContext context, string fileName)
        {
            //This ensures OutputCaching is set for this handler and also controls
            //client side caching on the browser side. Default is 10 days.
            TimeSpan        duration = TimeSpan.FromDays(10);
            HttpCachePolicy cache    = context.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(duration));
            cache.SetMaxAge(duration);
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(DateTime.Now);
            cache.SetETag(Guid.NewGuid().ToString());
            //set server OutputCache to vary by our params
            cache.VaryByParams["t"] = true;
            cache.VaryByParams["s"] = true;
            //don't allow varying by wildcard
            cache.SetOmitVaryStar(true);
            //ensure client browser maintains strict caching rules
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            //This is the only way to set the max-age cachability header in ASP.Net!
            FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);

            maxAgeField.SetValue(cache, duration);

            //make this output cache dependent on the file if there is one.
            if (!string.IsNullOrEmpty(fileName))
            {
                context.Response.AddFileDependency(fileName);
            }
        }
Пример #3
0
 public virtual void SetResponseCachePolicy
     (HttpCachePolicy cache)
 {
     cache.SetCacheability(HttpCacheability.NoCache);
     cache.SetNoStore();
     cache.SetExpires(DateTime.MinValue);
 }
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <param name="responseType">
        /// The HTTP MIME type to send.
        /// </param>
        /// <param name="dependencyPaths">
        /// The dependency path for the cache dependency.
        /// </param>
        private void SetHeaders(HttpContext context, string responseType, IEnumerable <string> dependencyPaths)
        {
            HttpResponse response = context.Response;

            response.ContentType = responseType;

            if (response.Headers["Image-Served-By"] == null)
            {
                response.AddHeader("Image-Served-By", "ImageProcessor.Web/" + AssemblyVersion);
            }

            HttpCachePolicy cache = response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.VaryByHeaders["Accept-Encoding"] = true;

            context.Response.AddFileDependencies(dependencyPaths.ToArray());
            cache.SetLastModifiedFromFileDependencies();

            int maxDays = DiskCache.MaxFileCachedDuration;

            cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
            cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            context.Items[CachedResponseTypeKey]        = null;
            context.Items[CachedResponseFileDependency] = null;
        }
Пример #5
0
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <param name="responseType">
        /// The HTTP MIME type to send.
        /// </param>
        /// <param name="dependencyPaths">
        /// The dependency path for the cache dependency.
        /// </param>
        private void SetHeaders(HttpContext context, string responseType, IEnumerable <string> dependencyPaths)
        {
            if (this.imageCache != null)
            {
                HttpResponse response = context.Response;

                if (response.Headers["ImageProcessedBy"] == null)
                {
                    response.AddHeader("ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion);
                }

                HttpCachePolicy cache = response.Cache;
                cache.SetCacheability(HttpCacheability.Public);
                cache.VaryByHeaders["Accept-Encoding"] = true;

                if (!string.IsNullOrWhiteSpace(responseType))
                {
                    response.ContentType = responseType;
                }

                if (dependencyPaths != null)
                {
                    context.Response.AddFileDependencies(dependencyPaths.ToArray());
                    cache.SetLastModifiedFromFileDependencies();
                }

                int maxDays = this.imageCache.MaxDays;

                cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
                cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
                cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

                this.imageCache = null;
            }
        }
Пример #6
0
        /// <summary>设置缓存策略(使用context.Response.Cache来缓存输出)</summary>
        /// <remarks>
        /// ashx 的页面缓存不允许写语句:<%@ OutputCache Duration="60" VaryByParam="*" %>
        /// 故可直接调用本方法实现缓存。
        /// 参考:https://stackoverflow.com/questions/1109768/how-to-use-output-caching-on-ashx-handler
        /// </remarks>
        public static void SetCachePolicy(this HttpResponse response, int cacheSeconds, string varyByParam = "*", HttpCacheability cacheLocation = HttpCacheability.ServerAndPrivate)
        {
            HttpCachePolicy cachePolicy = response.Cache;

            if (cacheSeconds > 0)
            {
                cachePolicy.SetCacheability(cacheLocation);
                cachePolicy.SetExpires(DateTime.Now.AddSeconds((double)cacheSeconds));
                cachePolicy.SetSlidingExpiration(false);
                cachePolicy.SetValidUntilExpires(true);
                if (varyByParam.IsNotEmpty())
                {
                    cachePolicy.VaryByParams[varyByParam] = true;
                }
                else
                {
                    cachePolicy.VaryByParams.IgnoreParams = true;
                }
            }
            else
            {
                cachePolicy.SetCacheability(HttpCacheability.NoCache);
                cachePolicy.SetMaxAge(TimeSpan.Zero);
            }
        }
Пример #7
0
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// See http://en.wikipedia.org/wiki/HTTP_ETag
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <param name="responseType">The HTTP MIME type to to send.</param>
        private void SetHeaders(HttpContext context, string responseType)
        {
            HttpResponse response = context.Response;

            response.ContentType = responseType;

            response.AddHeader("Image-Served-By", "ImageProcessor.Web/" + AssemblyVersion);

            HttpCachePolicy cache = response.Cache;

            cache.VaryByHeaders["Accept-Encoding"] = true;

            int maxDays = DiskCache.MaxFileCachedDuration;

            cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
            cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            string incomingEtag = context.Request.Headers["If-None-Match"];

            cache.SetCacheability(HttpCacheability.Public);

            if (incomingEtag == null)
            {
                return;
            }

            response.Clear();
            response.StatusCode      = (int)HttpStatusCode.NotModified;
            response.SuppressContent = true;
        }
Пример #8
0
        private void ProcessDefaultThumbnail()
        {
            // Generate the default album thumbnail and send to client.
            Bitmap bmp = null;

            try
            {
                this._context.Response.ContentType = "image/jpeg";

                HttpCachePolicy cachePolicy = this._context.Response.Cache;
                cachePolicy.SetExpires(DateTime.Now.AddSeconds(2592000));                 // 30 days
                cachePolicy.SetCacheability(HttpCacheability.Public);
                cachePolicy.SetValidUntilExpires(true);

                bmp = GetDefaultThumbnailBitmap();
                bmp.Save(_context.Response.OutputStream, ImageFormat.Jpeg);
            }
            finally
            {
                if (bmp != null)
                {
                    bmp.Dispose();
                }
            }
        }
Пример #9
0
        private void ProcessMediaObject()
        {
            // Send the specified file to the client.
            try
            {
                this._context.Response.Clear();
                this._context.Response.AddHeader("Content-Disposition", string.Format("inline;filename=\"{0}\"", MakeFileNameDownloadFriendly(Path.GetFileName(MediaObjectFilePath))));
                this._context.Response.ContentType = MimeType.FullType;
                this._context.Response.Buffer      = false;

                HttpCachePolicy cachePolicy = this._context.Response.Cache;
                cachePolicy.SetExpires(DateTime.Now.AddSeconds(2592000));                 // 30 days
                cachePolicy.SetCacheability(HttpCacheability.Public);
                cachePolicy.SetValidUntilExpires(true);

                FileStream fileStream = null;
                try
                {
                    byte[] buffer = new byte[_bufferSize];

                    try
                    {
                        fileStream = File.OpenRead(MediaObjectFilePath);
                    }
                    catch (ArgumentException) { return; }                                // If the file or directory isn't found, just return. This helps avoid clogging the error log
                    catch (FileNotFoundException) { return; }                            // with entries caused by search engine retrieving media objects that have been moved or deleted.
                    catch (DirectoryNotFoundException) { return; }

                    // Required for Silverlight to properly work
                    this._context.Response.AddHeader("Content-Length", fileStream.Length.ToString(CultureInfo.InvariantCulture));

                    int byteCount;
                    while ((byteCount = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        if (this._context.Response.IsClientConnected)
                        {
                            this._context.Response.OutputStream.Write(buffer, 0, byteCount);
                            this._context.Response.Flush();
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                finally
                {
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                AppErrorController.LogError(ex);
            }
        }
Пример #10
0
        private static void SetCache(string path)
        {
            HttpCachePolicy cache   = HttpContext.Current.Response.Cache;
            TimeSpan        expires = TimeSpan.FromDays(14);

            cache.SetExpires(DateTime.Now.Add(expires));
            cache.SetMaxAge(expires);
            cache.SetLastModified(File.GetLastWriteTime(path));
        }
Пример #11
0
        public void ProcessRequest(HttpContext context)
        {
            string name = context.Request.QueryString["f"];

            System.IO.Stream resource;
            HttpCachePolicy  cache = context.Response.Cache;

            // since the same instance is reused, reset these defaults
            _canZip = true; _canMinify = false;

            if (name == null)
            {
                return;
            }

            resource = _assembly.GetManifestResourceStream(
                string.Format("{0}.{1}.{2}", _nameSpace, _path, name));

            if (resource != null)
            {
                cache.SetCacheability(HttpCacheability.Public);
                cache.VaryByParams["f"] = true;
                cache.VaryByParams["t"] = true;
                cache.SetExpires(DateTime.Now.AddYears(1));
                context.Response.ContentType = this.InferMimeType(name);

                if (_canMinify)
                {
                    EcmaScriptMinify em = new EcmaScriptMinify();
                    em.WriteMinified(resource, context.Response.Output);
                }
                else
                {
                    byte[] buffer       = new byte[1025];
                    int    bytesToWrite = 1;
                    Stream output;

                    if (_canZip && _allowZip)
                    {
                        context.Response.AddHeader("Content-encoding", "gzip");
                        output = new GZipStream(context.Response.OutputStream, CompressionMode.Compress);
                    }
                    else
                    {
                        output = context.Response.OutputStream;
                    }
                    while (bytesToWrite > 0)
                    {
                        bytesToWrite = resource.Read(buffer, 0, 1024);
                        output.Write(buffer, 0, bytesToWrite);
                    }
                    resource.Dispose();
                    output.Dispose();
                }
            }
        }
Пример #12
0
 /// <summary>
 /// Set the response cache headers for WebResource
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="etag"></param>
 /// <param name="maxAge"></param>
 protected static void SetCachingHeadersForWebResource(HttpCachePolicy cache, string etag, TimeSpan maxAge)
 {
     cache.SetCacheability(HttpCacheability.Public);
     cache.VaryByParams["d"] = true;
     cache.SetOmitVaryStar(true);
     cache.SetExpires(DateTime.Now.Add(maxAge));
     cache.SetValidUntilExpires(true);
     cache.VaryByHeaders["Accept-Encoding"] = true;
     cache.SetETag(string.Concat("\"", etag, "\""));
 }
Пример #13
0
        /// <summary>设置页面缓存</summary>
        /// <param name="context">网页上下文</param>
        /// <param name="cacheSeconds">缓存秒数</param>
        /// <param name="varyByParam">缓存参数名称</param>
        /// <remarks>
        /// ashx 的页面缓存不允许写语句:<%@ OutputCache Duration="60" VaryByParam="*" %>
        /// 故可直接调用本方法实现缓存。
        /// 参考:https://stackoverflow.com/questions/1109768/how-to-use-output-caching-on-ashx-handler
        /// </remarks>
        public static void SetCache(HttpContext context, int cacheSeconds = 60, HttpCacheability cacheLocation = HttpCacheability.ServerAndPrivate, string varyByParam = "*")
        {
            TimeSpan        ts          = new TimeSpan(0, 0, 0, cacheSeconds);
            HttpCachePolicy cachePolicy = context.Response.Cache;

            cachePolicy.SetCacheability(cacheLocation);
            cachePolicy.VaryByParams[varyByParam] = true;
            cachePolicy.SetExpires(DateTime.Now.Add(ts));
            cachePolicy.SetMaxAge(ts);
            cachePolicy.SetValidUntilExpires(true);
        }
Пример #14
0
 private static void SetCache(HttpCachePolicy cache)
 {
     cache.SetCacheability(HttpCacheability.Public);
     cache.VaryByParams[_paramV]    = true;
     cache.VaryByParams[_paramFile] = true;
     cache.SetOmitVaryStar(true);
     cache.SetValidUntilExpires(true);
     cache.SetExpires(DateTime.Now.AddYears(2));
     cache.SetLastModified(DateTime.ParseExact(AppConstants.BuildDate,
                                               _dateFormat, CultureInfo.GetCultureInfo(_usCulture).DateTimeFormat));
 }
Пример #15
0
        private static void OutputCacheResponse(HttpContext context, DateTime lastModified)
        {
            HttpCachePolicy cachePolicy = context.Response.Cache;

            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.VaryByParams["*"] = true;
            cachePolicy.SetOmitVaryStar(true);
            cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365));
            cachePolicy.SetValidUntilExpires(true);
            cachePolicy.SetLastModified(lastModified);
        }
        /// <summary>
        /// 缓存
        /// </summary>
        /// <param name="instance">HttpContext扩展</param>
        /// <param name="durationInMinutes">时间</param>
        public static void CacheKD(this HttpContext instance, int durationInMinutes)
        {
            instance.CheckOnNull("instance");
            TimeSpan        duration = TimeSpan.FromMinutes(durationInMinutes);
            HttpCachePolicy cache    = instance.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(duration));
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            cache.SetMaxAge(duration);
        }
Пример #17
0
        private void SetCache(HttpCachePolicy cache, DateTime lastModified)
        {
            // Use ASP.Net output cache.

            cache.SetExpires(DateTime.UtcNow.Add(_imageProviderPath.Expiration));
            cache.SetValidUntilExpires(true);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetMaxAge(_imageProviderPath.Expiration);
            cache.SetLastModified(lastModified.ToUniversalTime());
            cache.SetETagFromFileDependencies();
        }
Пример #18
0
        private void ProcessMediaObject()
        {
            // Send the specified file to the client.
            try
            {
                IMimeType mimeType = MimeType.LoadInstanceByFilePath(this._filename);

                this._context.Response.Clear();
                this._context.Response.ContentType = mimeType.FullType;
                this._context.Response.Buffer      = false;

                HttpCachePolicy cachePolicy = this._context.Response.Cache;
                cachePolicy.SetExpires(DateTime.Now.AddSeconds(2592000));                 // 30 days
                cachePolicy.SetCacheability(HttpCacheability.Public);
                cachePolicy.SetValidUntilExpires(true);

                FileStream fileStream = null;
                try
                {
                    int    bufferSize = Config.GetCore().MediaObjectDownloadBufferSize;
                    byte[] buffer     = new byte[bufferSize];
                    fileStream = File.OpenRead(this._filepath);

                    // Required for Silverlight to properly work
                    this._context.Response.AddHeader("Content-Length", fileStream.Length.ToString());

                    int byteCount;
                    while ((byteCount = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        if (this._context.Response.IsClientConnected)
                        {
                            this._context.Response.OutputStream.Write(buffer, 0, byteCount);
                            this._context.Response.Flush();
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                finally
                {
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                AppErrorController.LogError(ex);
            }
        }
Пример #19
0
    public static void Cache(TimeSpan duration)
    {
        HttpCachePolicy cache = HttpContext.Current.Response.Cache;

        FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);

        maxAgeField.SetValue(cache, duration);

        cache.SetCacheability(HttpCacheability.Public);
        cache.SetExpires(DateTime.Now.Add(duration));
        cache.SetMaxAge(duration);
        cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
    }
        protected override void OnStartProcessingRequest(ProcessRequestArgs args)
        {
            //Cache for a minute based on querystring
            HttpContext     context = HttpContext.Current;
            HttpCachePolicy c       = HttpContext.Current.Response.Cache;

            c.SetCacheability(HttpCacheability.ServerAndPrivate);
            c.SetExpires(HttpContext.Current.Timestamp.AddSeconds(60));
            c.VaryByHeaders["Accept"]          = true;
            c.VaryByHeaders["Accept-Charset"]  = true;
            c.VaryByHeaders["Accept-Encoding"] = true;
            c.VaryByParams["*"] = true;
        }
Пример #21
0
        private void SetResponseCache(HttpContext context)
        {
            HttpCachePolicy cache = context.Response.Cache;

            cache.SetLastModified(new DateTime(ResourceManager.GetAssemblyTime(typeof(ResourceManager).Assembly)));
            cache.SetOmitVaryStar(true);
            cache.SetVaryByCustom("v");
            cache.SetExpires(DateTime.UtcNow.AddYears(1));
            cache.SetMaxAge(TimeSpan.FromDays(365));
            cache.SetValidUntilExpires(true);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.Public);
        }
Пример #22
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request      = context.Request;
            string      physicalPath = request.PhysicalPath;

            if (File.Exists(physicalPath))
            {
                string       subfix        = Path.GetExtension(physicalPath);
                bool         isOutputCache = false;
                HttpResponse response      = context.Response;
                if (".png".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    isOutputCache        = true;
                    response.ContentType = "image/x-png";
                }
                else if (".jpg".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    isOutputCache        = true;
                    response.ContentType = "image/pjpeg";
                }
                if (isOutputCache)
                {
                    const int DAYS            = 30;
                    string    ifModifiedSince = request.Headers["If-Modified-Since"];
                    if (!string.IsNullOrEmpty(ifModifiedSince) &&
                        TimeSpan.FromTicks(DateTime.Now.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Days < DAYS)
                    {
                        response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                        response.StatusDescription = "Not Modified";
                        response.End();
                        return;
                    }
                    else
                    {
                        HttpCachePolicy cache = response.Cache;
                        cache.SetLastModifiedFromFileDependencies();
                        cache.SetETagFromFileDependencies();
                        cache.SetCacheability(HttpCacheability.Public);
                        cache.SetExpires(DateTime.Now.AddDays(DAYS));
                        TimeSpan timeSpan = TimeSpan.FromDays(DAYS);
                        cache.SetMaxAge(timeSpan);
                        cache.SetProxyMaxAge(timeSpan);
                        cache.SetLastModified(context.Timestamp);
                        cache.SetValidUntilExpires(true);
                        cache.SetSlidingExpiration(true);
                    }
                }
                response.WriteFile(physicalPath);
                response.End();
            }
        }
        /// <summary>
        /// 缓存
        /// </summary>
        /// <param name="instance">HttpContext扩展</param>
        /// <param name="duration">时间差</param>
        public static void Cache(this HttpContext instance, TimeSpan duration)
        {
            instance.CheckOnNull("instance");
            HttpCachePolicy cache = instance.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetOmitVaryStar(true);
            cache.SetExpires(instance.Timestamp.Add(duration));
            cache.SetMaxAge(duration);
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(instance.Timestamp);
            cache.SetLastModifiedFromFileDependencies();
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        }
Пример #24
0
        private void SetResponseCache(HttpContext context)
        {
            HttpCachePolicy cache = context.Response.Cache;

            cache.SetLastModified(DateTime.Now.ToUniversalTime().AddSeconds(-1.0));
            cache.SetOmitVaryStar(true);
            cache.SetVaryByCustom("v");
            cache.SetExpires(DateTime.UtcNow.AddDays(365.0));
            cache.SetMaxAge(TimeSpan.FromDays(365.0));
            cache.SetValidUntilExpires(true);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetLastModifiedFromFileDependencies();
        }
Пример #25
0
 internal static void SetCacheLastModified(HttpContext context, DateTime lastModifiedTime, bool neverExpires)
 {
     if (lastModifiedTime.ToUniversalTime() < DateTime.UtcNow)
     {
         HttpCachePolicy cache = context.Response.Cache;
         cache.SetCacheability(HttpCacheability.Public);
         cache.SetLastModified(lastModifiedTime);
         if (neverExpires)
         {
             cache.SetExpires(DateTime.Now.AddYears(1));
             cache.SetValidUntilExpires(true);
         }
     }
 }
Пример #26
0
        /// <summary>
        /// Sets a response to be cached for a given amount of time following the initial request, allowing both shared and private caches
        /// </summary>
        /// <param name="cachePolicy">The response.</param>
        /// <param name="currentTime">The current time.</param>
        /// <param name="cacheExpiryTime">The cache expiry time.</param>
        /// <param name="responseIsIdenticalForEveryUser">if set to <c>true</c> one user may receive a response that was prepared for another user.</param>
        /// <exception cref="System.ArgumentNullException">cachePolicy</exception>
        /// <remarks>This method is for use with ASP.NET WebForms</remarks>
        public void CacheUntil(HttpCachePolicy cachePolicy, DateTime currentTime, DateTime cacheExpiryTime, bool responseIsIdenticalForEveryUser = true)
        {
            if (cachePolicy == null)
            {
                throw new ArgumentNullException("cachePolicy");
            }

            // Max-Age is the current standard, and Expires is the older one
            cachePolicy.SetMaxAge(cacheExpiryTime.Subtract(currentTime));
            cachePolicy.SetExpires(cacheExpiryTime);

            // Public allows caching on shared proxies as well as users' own browsers
            cachePolicy.SetCacheability(responseIsIdenticalForEveryUser ? HttpCacheability.Public : HttpCacheability.Private);
        }
Пример #27
0
        protected override void OnStartProcessingRequest(ProcessRequestArgs args)
        {
            base.OnStartProcessingRequest(args);

            HttpContext context = HttpContext.Current;

            if (null != context)
            {
                HttpCachePolicy c = context.Response.Cache;
                c.SetCacheability(HttpCacheability.ServerAndPrivate);
                c.SetExpires(context.Timestamp.AddSeconds(30));
                c.VaryByHeaders["Accept"]          = true;
                c.VaryByHeaders["Accept-Charset"]  = true;
                c.VaryByHeaders["Accept-Encoding"] = true;
                c.VaryByParams["*"] = true;
            }
        }
        /// <summary>
        /// When overridden in a derived class, returns a read-only stream to the virtual resource.
        /// </summary>
        /// <returns>
        /// A read-only stream to the virtual file.
        /// </returns>
        public override Stream Open()
        {
            // Set the response headers here. It's a bit hacky.
            HttpCachePolicy cache = HttpContext.Current.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.VaryByHeaders["Accept-Encoding"] = true;

            IFileSystem azureBlobFileSystem = FileSystemProviderManager.Current.GetUnderlyingFileSystemProvider("media");
            int         maxDays             = ((AzureBlobFileSystem)azureBlobFileSystem).FileSystem.MaxDays;

            cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
            cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            return(this.stream());
        }
        protected override void OnStartProcessingRequest(ProcessRequestArgs args)
        {
            base.OnStartProcessingRequest(args);

            HttpCachePolicy c = HttpContext.Current.Response.Cache;

            c.SetCacheability(HttpCacheability.ServerAndPrivate);

            c.SetExpires(HttpContext.Current.Timestamp.AddSeconds(600));

            c.VaryByHeaders["Accept"]          = true;
            c.VaryByHeaders["Accept-Charset"]  = true;
            c.VaryByHeaders["Accept-Encoding"] = true;
            c.VaryByParams["*"] = true;

            // don't allow clients to mess with this. its valid period
            c.SetValidUntilExpires(true);
        }
Пример #30
0
        private static void SetCache(bool suppressLastModified = false)
        {
            HttpContext.Current.Response.AddHeader("Age", ((int)(PortalContext.Current.LastModified - DateTime.Now).TotalSeconds).ToString(CultureInfo.InvariantCulture));
            HttpCachePolicy cache   = HttpContext.Current.Response.Cache;
            TimeSpan        expires = TimeSpan.FromDays(14);

            cache.SetExpires(DateTime.UtcNow.Add(expires));
            cache.SetMaxAge(expires);
            DateTime dt       = PortalContext.Current.LastModified;
            string   eTagDate = "\"" + dt.ToString("s", DateTimeFormatInfo.InvariantInfo) + "\"";

            HttpContext.Current.Response.AddHeader("ETag", eTagDate);

            if (!suppressLastModified)
            {
                cache.SetLastModified(PortalContext.Current.LastModified);
            }
        }