Home > Blockchain >  .NET Core API update cached image if newer
.NET Core API update cached image if newer

Time:11-25

We have multi tenant applications and now the client wants every tenant to have their own logo, uploadable from the admin application. Now in order to not download the image every time the application is opened I'll tell the browser to cache it.

Now the problem is, how to tell the browser from the API when there is new logo uploaded? I'll keep the upload date in the database, but how do I use that so the browser will download the new image if needed? Or I need some other information I can use?

CodePudding user response:

You can do it like this:

[HttpGet]
public IActionResult Logo()
{
    // Mock value. Get actual upload date from the db here
    DateTime uploadDate = new DateTime(2021, 11, 24, 0, 0, 0, DateTimeKind.Utc); 

    if (Request.GetTypedHeaders().IfModifiedSince?.UtcDateTime >= uploadDate)
    {
        return StatusCode(StatusCodes.Status304NotModified);
    }

    // Mock value. Get actual image bytes from the db/disk here
    byte[] bytes = new byte[0];

    ResponseHeaders responseHeaders = Response.GetTypedHeaders();
    responseHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true };
    responseHeaders.LastModified = new DateTimeOffset(uploadDate);

    return File(bytes, "image/png");
}

First you get image bytes and upload date. Then you compare value of If-Modified-Since header (it will be set automatically by a browser) with the upload date. If uploadDate is not older than this value, that means browser cache already contains up-to-date image and you can respond with 304 Not Modified. Otherwise, you set Cache-Control header to no-cache (that forces browser to ask your API whether cached image is still valid on each request) and set Last-Modified header to the uploadDate. Browser will send this value in If-Modified-Since header on subsequent requests.

Note: make sure you use right timezone when comparing dates.

  • Related