Hey folks, well recently i developed some web service that return image as file from a web service method. User pass us a URL like below:

http://www.abc.com/api/downloadfile?fileid=100&type=user

This return image of user with id=100

Lets 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 page stays busy until all images are loaded.

To tackle this, all i did was below HIGHLIGHTED IN BOLD:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
        [HttpGet]
        [EnableCors(origins: "*", headers: "*", methods: "get", PreflightMaxAge = 600)]
        [Route("DownloadFile")]
        [Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]
        public async Task<httpresponsemessage> DownloadFile(int FileId)
        {
            var result = Task.Factory.StartNew(() =>
            {
                var regact = DownloadFileContent(FileId); //returns us the bytes of file based on Id provided.
                return regact;
            });
 
            await result;
 
            if (result.Result == null)
            {
                HttpResponseMessage resultNoFile = new HttpResponseMessage(HttpStatusCode.NoContent);
                return resultNoFile;
            }
            else
            {
                byte[] fileContent = Convert.FromBase64String(result.Result.DocumentBody);
 
                HttpResponseMessage results = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new System.IO.MemoryStream(fileContent);
                results.Content = new StreamContent(stream);
                results.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(result.Result.MimeType);
 
                results.Headers.CacheControl = new CacheControlHeaderValue
                {
                    Public = true,
                    MaxAge = TimeSpan.FromSeconds(259200)
                };
 
                results.Headers.Add("Cache-Control", "public, max-age=259200");
                return results;
            }
        }
</httpresponsemessage>

Added following attribute to method

[Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]

and following chunk into the code block.

results.Headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = TimeSpan.FromSeconds(259200)
};

results.Headers.Add(“Cache-Control”, “public, max-age=259200”);

After this first time we load images from service and next time from disk cache.