How not to abort http response c#

前端 未结 8 691
刺人心
刺人心 2020-12-18 03:34

I need to run several methods after sending file to a user for a download. What happens is that after I send a file to a user, response is aborted and I can no longer do any

8条回答
  •  一整个雨季
    2020-12-18 03:57

    the user clicks on a download button on WebForm1.aspx to start downloading a file. then, after the file download is done (served by WebForm2.aspx), user is automatically redirected.

    WebForm1.aspx

    
    
    

    WebForm1.aspx.cs

    protected void btnDL_Click(object sender, EventArgs e)
    {
        var sent = Session["sent"];
    
        while (Session["sent"]==null)
        {// not sure if this is a bad idea or what but my cpu is NOT going nuts
        }
    
        StartNextMethod();
        Response.Redirect(URL);
    
    }
    

    WebForm2.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;  filename=test.pdf");
        Response.ContentType = "application/pdf";
        byte[] a = System.Text.Encoding.UTF8.GetBytes("test");
        Response.BinaryWrite(a);
        Session["sent"] = true;
    }
    

    Global.asax.cs

    protected void Session_Start(object sender, EventArgs e)
    {
        Session["init"] = 0; // init and allocate session data storage
    }
    

    note: make sure don't use ashx (generic handler) to serve your download. for some reason, the session in ashx and aspx don't talk to each other, unless you implement this.

提交回复
热议问题