Search code examples
c#jqueryasp.netashx

ASP.NET Handler not working properly


I created an Ashx handler in C# that serves me up images based on a fileid parameter that gets passed on to me. I also have a simple tooltip preview script that I wrote, which is not working. You can see the image loading, but then after it loads, the image just vanishes.

I suspect the issue is in the ASHX handler because if I use a static image, it works just fine. Here is my ASHX handler code:

    public void ProcessRequest(HttpContext context)
    {
        string fileId = HttpUtility.UrlDecode(context.Request.QueryString["fileId"] ?? "") ?? "";
        string fullFileName = context.Server.MapPath("~/Uploads") + "\\" + fileId;

        using (FileStream s = File.Open(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            context.Response.ContentType = HelperClasses.Utility.GetMimeTypeFromMagic(fullFileName);

            var buffer = new byte[s.Length];
            s.Read(buffer, 0, (int) s.Length);

            context.Response.BinaryWrite(buffer);
            context.Response.Write(buffer);

            s.Close();
        }
        context.Response.Flush();
        context.Response.Close();
    }

In addition, I've created a fiddle to demonstrate the issue.


Solution

  • In your code, the line

    context.Response.Close();

    is the issue. The close method abruptly ends the response stream, see details here and also check this related question IIS & Chrome: failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

    Replace the line with context.Response.End(); to normally end the response.