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:
- [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;
- }
- }
[Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]
and the 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”);

Ano MepaniPosted Aug 6, 2019, 11:47 AM
Does response cache on server side or on client side.? Does it affects server?
Mahesh ChandPosted Aug 6, 2019, 11:10 AM
This blog belongs to Web API category. Please move.
Amit MohantyPosted Aug 6, 2019, 5:17 AM
Nice. Thanks for sharing
Madan ShekarPosted Aug 6, 2019, 4:12 AM
Good information .. .thanks for sharing
Deepak TewatiaPosted Aug 6, 2019, 3:39 AM
Nice... thanks sir for sharing this.