简体   繁体   中英

How can i count image views in ASP.NET MVC

I want intercept all request for image files, but i am not getting a way to do it,

One way is to create an action in MVC controller and return all image files from it,

 public HttpResponseMessage Get(Guid id)
    {
        var path = HttpContext.Current.Server.MapPath(string.Format("/OriginalImages/{0}.jpg", id));
        byte[] fileData = File.Exists(path) ? File.ReadAllBytes(path) : new byte[0];
        MemoryStream ms = new MemoryStream(fileData);
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(ms.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
        return  result;
    }

but it does not seems good idea as i noted that image access request completing in 15-20 milliseconds, while direct image access via path takes 5-6 milliseconds.

I tried using Owin Middleware, but it do not get executed on image file requests.

How can i achieve this? I want to increment view count of image file by this.

You would have to configure IIS (either through the IIS management interface or the application web.conifg) so it maps service all requests for images through ASP.NET. Then write a handler that will do whatever you want when the image is requested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM