ASPX That Returns An Image - Output Cache-able?
Asked Answered
C

3

6

Greetings!

I've created an APSX web form that returns a remote image based on some supplied parameters. It can be used like this:

<img src="/ImageGetter.aspx?param1=abc&param2=123" />

ImageGetter.aspx's markup and code look similar to this:

<%@ OutputCache Duration="100000" VaryByParam="*" Location="ServerAndClient" %>
<%@ Page Language="C#" AutoEventWireup="false" EnableSessionState="False" CodeBehind="ImageGetter.aspx.cs" Inherits="ACME.Helpers.ImageGetter" %>

This code is called in ImageGetter.aspx's Page_Load method:

byte[] data = null;
Dictionary<string, string> file_locations = GetImageLocations(param1, param2);
try
{
    data = new WebClient().DownloadData(file_locations["main"]);
}
catch (WebException wex)
{
    try
    {
        data = new WebClient().DownloadData(file_locations["backup"]);
    }
    catch (Exception e)
    {
        throw;
    }
}
Response.ContentType = "image/jpeg";
Response.OutputStream.Write(data, 0, data.Length);
Response.End();

From my testing, it doesn't appear to be caching. Is this possible to do with Output Caching or should I resort to writing my own cache to store the byte arrays depending on query string paramters?

Curriculum answered 13/4, 2009 at 21:35 Comment(0)
M
10

Try dropping the Response.End() as this will terminate the thread prematurely and prevent output caching from taking place.

See: http://bytes.com/groups/net-asp/323363-cache-varybyparam-doesnt-work

You may wish to consider using an ASHX handler and using your own caching method.

Montsaintmichel answered 13/4, 2009 at 21:51 Comment(2)
Dropping Response.End somehow slows it down even more so.Curriculum
...because its now jumping through cache hoops?Montsaintmichel
T
2

Use an ASHX generic handler and use the HttpRuntimeCache (Cache object) to do the job as Codebrain said. It will be faster and WAY more flexible.

Typewritten answered 13/4, 2009 at 23:56 Comment(0)
R
0

Your problem could be a bug in IE - it can't cache if the Vary:* HTTP response header is used, but IIS returns it by default because it's in the HTTP 1.1 spec.

Try adding the following to your web.config:

<system.web> 
    <caching>
        <outputCache omitVaryStar="true" />
    </caching>
</system.web> 
Reider answered 8/6, 2010 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.