how to make code execute after Response.end

后端 未结 4 1137
感动是毒
感动是毒 2021-01-03 11:53

My code is like this

HttpContext.Current.Response.Clear();
     HttpContext.Current.Response.ContentType = \"application/pdf\";
     HttpContext.Current.Resp         


        
相关标签:
4条回答
  • 2021-01-03 12:30

    I had the same issue. try this: copy to MemoryStream -> delete file -> download.

    string absolutePath = "~/your path";
    try {
        //copy to MemoryStream
        MemoryStream ms = new MemoryStream();
        using (FileStream fs = File.OpenRead(Server.MapPath(absolutePath))) 
        { 
            fs.CopyTo(ms); 
        }
    
        //Delete file
        if(File.Exists(Server.MapPath(absolutePath)))
           File.Delete(Server.MapPath(absolutePath))
    
        //Download file
        Response.Clear()
        Response.ContentType = "image/jpg";
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + absolutePath + "\"");
        Response.BinaryWrite(ms.ToArray())
    }
    catch {}
    
    Response.End();
    
    0 讨论(0)
  • 2021-01-03 12:42

    HttpResponse.End (as per documentation) raises a ThreadAbortException and as you do no attempt to handle this your method exits.

    I'm not sure exactly why you must use End(), but you could put the "cleanup" code in a finally statement.

    0 讨论(0)
  • 2021-01-03 12:44
    // Add headers for a csv file or whatever
    Response.ContentType = "text/csv"
    Response.AddHeader("Content-Disposition", "attachment;filename=report.csv")
    Response.AddHeader("Pragma", "no-cache")
    Response.AddHeader("Cache-Control", "no-cache")
    
    // Write the data as binary from a unicode string
    Dim buffer As Byte()
    buffer = System.Text.Encoding.Unicode.GetBytes(csv)
    Response.BinaryWrite(buffer)
    
    // Sends the response buffer
    Response.Flush()
    
    // Prevents any other content from being sent to the browser
    Response.SuppressContent = True
    
    // Directs the thread to finish, bypassing additional processing
    HttpContext.Current.ApplicationInstance.CompleteRequest()
    
    0 讨论(0)
  • 2021-01-03 12:45

    Maybe fire some async method (fire and forget style) to delete the file or have a clean-up service on the server to delete all your files after certain time and rule.

    Like mentioned about Reponse.End is pretty harsh and final... more details here: Is Response.End() considered harmful?

    just my thoughts on that... =)

    0 讨论(0)
提交回复
热议问题