使用IHttpModule添加ETag

时间:2014-06-29 19:23:33

标签: asp.net httpmodule etag

我写了一个简单的IHttpModule

void context_PreSendRequestHeaders(object sender, EventArgs e)
{
    //remove default
    HttpContext.Current.Response.Headers.Remove("ETag");

    //add version one
    HttpContext.Current.Response.Headers.Add("ETag", "Test1.0");
}

我想删除IIS ETag并添加我自己的用于控制来自客户端的javascript和css文件请求 - 如果是更新,我希望它会自动刷新。 客户对ETag的回应

  

If-None-Match:Test1.0   If-Modified-Since:Mon,02 Jun 2014 11:08:54 GMT

但IIS始终返回内容而不是304

1 个答案:

答案 0 :(得分:0)

void context_PreSendRequestHeaders(object sender, EventArgs e)
    {
        var etag = "Test4-0";

        //remove default
        HttpContext.Current.Response.Headers.Remove("ETag");

        //add version one
        HttpContext.Current.Response.Headers.Add("ETag", etag);

        string ifNoneMatch = HttpContext.Current.Request.Headers["If-None-Match"];
        Debug.WriteLine(String.Format("ifNoneMatch - {0}", ifNoneMatch));

        if (ifNoneMatch != null && ifNoneMatch.Contains(","))
        {
            ifNoneMatch = ifNoneMatch.Substring(0, ifNoneMatch.IndexOf(",", StringComparison.Ordinal));
        }

        HttpContext.Current.Response.Cache.VaryByHeaders["If-None-Match"] = true;
        Debug.WriteLine(String.Format("ifNoneMatch - etag: {0}-{1}", ifNoneMatch, etag));
        if (etag == ifNoneMatch)
        {
            Debug.WriteLine(String.Format("ifNoneMatch2 - etag: {0}-{1}", ifNoneMatch, etag));
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotModified;
            HttpContext.Current.Response.SuppressContent = true;
        }
    }
}