62,025
社区成员
发帖
与我相关
我的任务
分享
using System;
namespace WebModule
{
using System.Web;
using System.IO.Compression;
using System.Text.RegularExpressions;
/// <summary>
/// Compresses the output using standard gzip/deflate.
/// eg:
/// <httpModules>
/// <add type="WebModule.CompressModule,WebHandler" name="CompressModule1" />
/// </httpModules>
/// </summary>
public class CacheModule : IHttpModule
{
void IHttpModule.Dispose()
{
// Nothing to dispose;
}
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
/// <summary>
/// 获取配置文件中要要启用缓存的拓展名
/// </summary>
private static string EXT = string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["CacheEXT"]) ? "jpg|gif" : System.Configuration.ConfigurationManager.AppSettings["CacheEXT"];
private static TimeSpan MAXAGE = new TimeSpan(7, 0, 0, 0);
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (!Regex.IsMatch(app.Request.FilePath, ".(?:" + EXT + ")$", RegexOptions.IgnoreCase))
return;
SetHeaders(System.IO.File.GetLastWriteTime(app.Server.MapPath(app.Request.FilePath)).GetHashCode(), app.Context, MAXAGE);
}
#region SetHeaders
/// <summary>
/// This will make the browser and server keep the output
/// in its cache and thereby improve performance.
/// </summary>
public static void SetHeaders(int hash, HttpContext context,TimeSpan maxAge)
{
//context.Response.ContentType = contentType;
context.Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
context.Response.Cache.SetExpires(DateTime.Now.ToUniversalTime().Add(maxAge));
context.Response.Cache.SetMaxAge(maxAge);
context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
string etag = "\"" + hash.ToString() + "\"";
context.Response.Cache.SetETag(etag);
if (String.Compare(context.Request.Headers["If-None-Match"], etag) == 0)
{
context.Response.Clear();
context.Response.StatusCode = (int)System.Net.HttpStatusCode.NotModified;
context.Response.SuppressContent = true;
}
}
#endregion
}
}