Search code examples
c#httpcontextashxgeneric-handler

Generic handler file download does not start


I'm trying to start downloading files from server, now just with some hardcoded values for files which exists but for some reason the download does not start and no error is thrown.

This is the code I have:

public void ProcessRequest(HttpContext context)
{
    string destPath = context.Server.MapPath("~/Attachments/cover.txt");
    // Check to see if file exist
    FileInfo fi = new FileInfo(destPath);

    if (fi.Exists)
    {
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + "cover.txt");
        HttpContext.Current.Response.BinaryWrite(ReadByteArryFromFile(destPath));
        HttpContext.Current.Response.End();
    }
}

public bool IsReusable
{
    get
    {
        return false;
    }
}

private byte[] ReadByteArryFromFile(string destPath)
{
    byte[] buff = null;
    FileStream fs = new FileStream(destPath, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    long numBytes = new FileInfo(destPath).Length;
    buff = br.ReadBytes((int)numBytes);
    return buff;
}

I'm stepping in the code and no problem is occurring but as well no file download popup is shown in the browser.

Do you see anything wrong?


Solution

  • I believe the issue your having is that your calling HttpContext.Current. Since your utilizing a Generic Handler File I believe you'll want to utilize the context parameter being passed to your method signature. An example would be:

    public void ProcessRequest (HttpContext context)
    {
         // Build Document and Zip:
         BuildAndZipDocument(); 
    
         // Context:
         context.Response.ContentType = "application/zip";
         context.Response.AddHeader("content-disposition", "filename="Commodity.zip");
         zip.Save(context.Response.OutputStream);
    
         // Close:
         context.Response.End();
    }
    

    I believe if you utilize context, rather than HttpContext.Current it will resolve your issue.