/// <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); } }
/// <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); } }
/// <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; } }
/// <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; }
private IObservable <Response> LoadWithLastModified(HttpCachePolicy policy, Uri uri, Options options, Dictionary <string, string> responseHeaders) { Log.Debug($"{policy} - LoadWithLastModified: {uri}"); var lastModified = responseHeaders.GetValueOrDefault(KnownHttpHeaders.LastModified); if (lastModified == null) { return(LoadFromCacheThenOrigin(policy, uri, options, responseHeaders)); } options.SetHeader(KnownHttpHeaders.IfModifiedSince, lastModified); if (policy == HttpCachePolicy.OriginIfETagOtherwiseCache) { return(LoadFromOrigin(policy, uri, options) .Catch <Response, HttpException>(ex => { Log.Debug( $"{policy} - Failed to retrieve {uri} from origin (Status: {ex.StatusCode}, Error: {ex}), falling back to cached version."); return LoadFromCache(policy, uri, responseHeaders); })); } // CacheThenOriginIfLastModified return(LoadFromCacheThenOrigin(policy, uri, options, responseHeaders)); }
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(); } } }
private IObservable <Response> LoadWithETag(HttpCachePolicy policy, Uri uri, Options options, Dictionary <string, string> responseHeaders) { Log.Debug($"{policy} - LoadWithETag: {uri}"); var eTag = responseHeaders.GetValueOrDefault(KnownHttpHeaders.ETag); if (eTag == null) { return(LoadFromOrigin(policy, uri, options)); } options.SetHeader(KnownHttpHeaders.IfNoneMatch, eTag); if (policy == HttpCachePolicy.OriginIfETagOtherwiseCache) { return(LoadFromOrigin(policy, uri, options) .Catch <Response, HttpException>(ex => { Log.Debug( $"{policy} - Failed to retrieve {uri} from origin (error: {ex}), falling back to cached version."); return LoadFromCache(policy, uri, responseHeaders); })); } // CacheThenOriginIfETag return(LoadFromCacheThenOrigin(policy, uri, options, responseHeaders)); }
/// <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; }
public virtual void SetResponseCachePolicy (HttpCachePolicy cache) { cache.SetCacheability(HttpCacheability.NoCache); cache.SetNoStore(); cache.SetExpires(DateTime.MinValue); }
public HttpCachePolicyWrapper(HttpCachePolicy httpCachePolicy) { if (httpCachePolicy == null) { throw new ArgumentNullException("httpCachePolicy"); } _httpCachePolicy = httpCachePolicy; }
private IObservable <Response> LoadFromCache(HttpCachePolicy policy, Uri uri, Dictionary <string, string> responseHeaders) { Log.Debug($"{policy} - Loading resource from cache: {uri}"); return(_httpCache .Load(uri) .Select(bytes => new Response(KnownStatusCode.Ok, () => bytes, responseHeaders))); }
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); } }
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)); }
internal CachedVaryBy (HttpCachePolicy policy, string key) { prms = policy.VaryByParams.GetParamNames (); headers = policy.VaryByHeaders.GetHeaderNames (policy.OmitVaryStar); custom = policy.GetVaryByCustom (); this.key = key; item_list = new List <string> (); wildCardParams = policy.VaryByParams ["*"]; }
public static HttpCacheability GetCacheability(this HttpCachePolicy self) { var type = self.GetType(); var flags = BindingFlags.Instance | BindingFlags.NonPublic; var cacheability = type.GetField("_cacheability", flags); return((HttpCacheability)cacheability.GetValue(self)); }
public static DateTime GetLastModified(this HttpCachePolicy self) { var type = self.GetType(); var flags = BindingFlags.Instance | BindingFlags.NonPublic; var cacheability = type.GetField("_utcLastModified", flags); return((DateTime)cacheability.GetValue(self)); }
internal CachedVaryBy(HttpCachePolicy policy, string key) { prms = policy.VaryByParams.GetParamNames(); headers = policy.VaryByHeaders.GetHeaderNames(policy.OmitVaryStar); custom = policy.GetVaryByCustom(); this.key = key; item_list = new List <string> (); wildCardParams = policy.VaryByParams ["*"]; }
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(); } } }
private IObservable <Response> LoadFromCacheThenOrigin(HttpCachePolicy policy, Uri uri, Options options, Dictionary <string, string> responseHeaders) { Log.Debug($"{policy} - LoadFromCacheThenOrigin: {uri}"); return(LoadFromCache(policy, uri, responseHeaders) .Concat(Observable.Defer(() => LoadFromOrigin(policy, uri, options) .Catch <Response, HttpException>(ex => ex.StatusCode == HttpStatusCode.NotModified ? Observable.Empty <Response>() : Observable.Throw <Response>(ex))))); }
/// <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, "\"")); }
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="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); }
/// <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); }
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)); }
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); } }
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(); }
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; }
/// <summary> /// Sets the caching used for resources on the http response cache policy. /// </summary> private static void SetCachingPolicy(HttpCachePolicy cachePolicy) { cachePolicy.SetCacheability(HttpCacheability.ServerAndPrivate); cachePolicy.SetNoServerCaching(); cachePolicy.SetMaxAge(TimeSpan.FromMinutes(5)); /* NOTE: The two calls below prevent resources from being stored on * disk but they also set the expiration to be immediate. Which means * that if we preload images (e.x., grid) then the next time they are * requested they will again go back to the server. So we cannot use these. */ // cachePolicy.SetNoStore(); // cachePolicy.SetCacheability(HttpCacheability.NoCache); }
/// <summary> /// Construtor padrão. /// </summary> /// <param name="context"></param> /// <param name="response"></param> /// <param name="request"></param> /// <param name="encoding">Encoding que será usado na reposta.</param> public HttpResponse(HttpContext context, Microsoft.Owin.IOwinResponse response, System.Web.HttpRequestBase request, System.Text.Encoding encoding) { _context = context; _response = response; _request = request; _encoding = encoding; _cookies = new System.Web.HttpCookieCollection(); _headers = new System.Collections.Specialized.NameValueCollection(); _response.OnSendingHeaders(SendHeaders, null); _writer = new HttpResponseWriter(response, encoding); _cache = new HttpCachePolicy(this); ContentType = response.ContentType; }
internal CachedRawResponse (HttpCachePolicy policy) { this.policy = policy; this.buffer = new byte [HttpWriter.MaxBufferSize]; }
public CachedRawResponse (HttpCachePolicy policy) { this.policy = policy; }