ETag implementation in ASP.Net Core - Part 3

Sunday, 22 August 2021
ASP.NET ETag REST API

In part two we created a simple application with as single REST endpoint. The client can calls the endpoint and show the requested resource. The resource changes periodically to simulate real situations. Now it is time to go to the next level.

Fortunately their is nothing to do in the client side since browsers take care of that area. To implement ETag in the server side, we use a custom action filter. Here is the code

public class ETagFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var reqHeaders = context.HttpContext.Request.Headers;
        if (reqHeaders.ContainsKey("If-None-Match"))
        {
            var etag = reqHeaders["If-None-Match"];
            var data = Data.GetData();
            if (data.Id == Int32.Parse(etag[0]))
            {
                context.Result = new StatusCodeResult(StatusCodes.Status304NotModified);
            }
        }
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        context.HttpContext.Response.Headers.Add("ETag", Data.GetData().Id.ToString());
    }
}

OnActionExecuting executes before the action method itself. The code first checks for If-None-Math. If it is not found or has an invalid value, the action method will be called normally. If the ETag value is valid, HTTP 304 will be returning meaning the cached data is still up-to-date and can be reused. By setting context.Result, the action method will not be called anymore (Read more here).

OnActionExecuted is called after the action method executes. Here we just need to set ETag header with the proper value so the new ETag value can be sent to clients.

Of course, what you saw here is not a perfect solution but it serves the its purpose which is gives you an idea how every pieces should behave.

Now let's run the new version for the first time and inspect the Firefox Network tab again.

image

The request is same as before. The response on the other hand has small but important difference. Notice the ETag header sent by the server.

Now let's refresh the page once again. Pay attention that you may need to refresh twice rapidly. Remember the resource is automatically modifies between 5 to 10 seconds. So if you wait too long, the server needs to send you a new version of the resource.

image

This time there is nothing interesting in headers but the response is very different. Its status code is 304 instead od 200 and the Transferred column shows the cached version is used and no data was transmitted over the network.

And that wraps up this topic. The source code can be found on Github.

Top