li-raz
li-raz

Reputation: 1696

Add ETag using IHttpModule

I have wrote a simple 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");
}

where I want to remove IIS ETag and add my own for controlling javascript and css file requests from clients - as in case of update I want it will be refreshed automatically. the client response ok to the ETag

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

but the IIS always returns the content instead of 304

Upvotes: 1

Views: 257

Answers (1)

li-raz
li-raz

Reputation: 1696

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;
        }
    }
}

Upvotes: 0

Related Questions