C-sharp Cache Image returned from asp.net webapi

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.

ASP.NET Core 2 Preview 1

ASP.NET Core 2.0.0-preview1

The next full version of ASP.NET Core is on its way, and developers who have been following along on the ASP.NET GitHub repositories have been very vocal about their interest in the new features in this version.  Some of these new features include:

  • A new ASP.NET Core meta-package that includes all features that you need to build an application. No longer do you need to pick and choose individual ASP.NET Core features in separate packages as all features are now included in a Microsoft.AspNetCore.All package in the default templates. If there are features you don’t need in your application, our new package trimming features will exclude those binaries in your published application output by default.
  • A new default Web Host configuration, codifying the typical defaults of the web host with the WebHost.CreateDefaultBuilder() API. This adds Kestrel, IIS configuration, default configuration sources, logging providers, and the content root.
  • Updated configuration and simplified logging. We have enhanced the LoggerFactory object to easily support a Dictionary<string, LogLevel> that defines log filters instead of a FilterLoggerSettings object, making it simpler to control the source and level of logs that get propagated from your application to your configured log providers.
  • Create pages without controllers in ASP.NET Core with the new RazorPages capabilities.  Just create a Pages folder and drop in a cshtml file with the new @page directive to get started.
  • Debugging your application in the cloud is easier than ever with integrated Azure Application Insights and diagnostics when debugging in Visual Studio and after deploying to Azure App Service.
  • A newly revamped authentication model that makes it easy to configure authentication for your application using DI.
  • New templates for configuring authentication for your web apps and web APIs using Azure AD B2C
  • New support in ASP.NET Core Identity for providing identity as a service. Updated templates decouple your apps from their identity concerns standard protocols (OpenID Connect, OAuth 2.0). Easily migrate apps using ASP.NET Core Identity for authentication to use Azure AD B2C or any other OpenID Connect compliant identity provider.
  • Build secure web APIs using ASP.NET Core Identity. Acquire access tokens for accessing your web APIs using the Microsoft Authentication Library (MSAL)
  • NET Core has always helped HTMLEncode your content by default, but with the new version we’re taking an extra step to help prevent cross-site request forgery (XSRF) attacks: ASP.NET Core will now emit anti-forgery tokens by default and validate them on form POST actions and pages without extra configuration.

For a full list of changes see the release notes.

MVC 3 & RAZOR crash course by Microsoft and HEC

14th and 15th Feb 2012

Higher education commission scheduled an event for All Pakistan university training for MVC 3, the attendees were subjected to be both university students and professors as well.

The event went well, we took deep insight into MVC and RAZOR in a 3 hours session each day.

14th Feb :

  1. Institute of Management Science Peshawar
  2. UET Taxila
  3. PIEAS
  4. Comsats University
  5. KPK Agriculture University
  6. Air University

15th Feb :

  1. Punjab University
  2. Kinnarid Collage Lahore
  3. Shaheed Benazir Bhutto University
  4. University of Health and Science
  5. Punjab University Collage of Information technology

I hope it went well for the attendees.