Cache Image Returned From ASP.Net WEB API

In this blog, we see how to properly cache an image returning from asp.net web API.

Hey folks, recently I developed some web service that returns images as files from a web service method. The user passes it as a URL like below:
 
http://www.abc.com/api/downloadfile?fileid=100&type=user
 
This returns an image of user with id=100
 
Let's say we list 100 users on a page, and bind this URL to image src attribute, whenever the page loads, it will make 110 calls to the service and the page stays busy until all images are loaded.
 
To tackle this, all I did is:
  1. [HttpGet]  
  2. [EnableCors(origins: "*", headers: "*", methods: "get", PreflightMaxAge = 600)]  
  3. [Route("DownloadFile")]  
  4. [Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]  
  5. public async Task < httpresponsemessage > DownloadFile(int FileId) {  
  6.  var result = Task.Factory.StartNew(() => {  
  7.   var regact = DownloadFileContent(FileId); //returns us the bytes of file based on Id provided.    
  8.   return regact;  
  9.  });  
  10.   
  11.  await result;  
  12.   
  13.  if (result.Result == null) {  
  14.   HttpResponseMessage resultNoFile = new HttpResponseMessage(HttpStatusCode.NoContent);  
  15.   return resultNoFile;  
  16.  } else {  
  17.   byte[] fileContent = Convert.FromBase64String(result.Result.DocumentBody);  
  18.   
  19.   HttpResponseMessage results = new HttpResponseMessage(HttpStatusCode.OK);  
  20.   var stream = new System.IO.MemoryStream(fileContent);  
  21.   results.Content = new StreamContent(stream);  
  22.   results.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(result.Result.MimeType);  
  23.   
  24.   results.Headers.CacheControl = new CacheControlHeaderValue {  
  25.    Public = true,  
  26.     MaxAge = TimeSpan.FromSeconds(259200)  
  27.   };  
  28.   
  29.   results.Headers.Add("Cache-Control""public, max-age=259200");  
  30.   return results;  
  31.  }  
  32. }  
I added the following attribute to the method:
 
[Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]
 
and the following chunk into the code block:
  1. results.Headers.CacheControl = new CacheControlHeaderValue  
  2. {  
  3.     Public = true,  
  4.     MaxAge = TimeSpan.FromSeconds(259200)  
  5. };  
  6. results.Headers.Add(“Cache-Control”, “public, max-age=259200”);  
After this first time, we load images from service and next time from the disk cache.