【问题标题】:Exception generated by Response.End()Response.End() 产生的异常
【发布时间】:2013-10-06 07:32:36
【问题描述】:

我让用户使用以下代码下载文件。它工作正常但也会产生错误,错误来源是Response.End();

错误消息无法计算表达式,因为代码已优化或本机框架位于调用堆栈顶部。`

下面是我的代码。我该如何处理这个错误?这个错误是否不会释放我的资源,从而导致不必要的内存使用。

我将它用于 asp.net webform 应用程序。

    try
    {
        string fileName = Request["file_ID"];
        string path = Server.MapPath("~/App_Data/uploads/"+fileName);


        //string = Server.MapPath(strRequest); 
        System.IO.FileInfo file = new System.IO.FileInfo(path);
        if (file.Exists)
        {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/"+file.Extension;
            Response.WriteFile(file.FullName);
            Response.End();

            // System.Threading.Thread.Sleep(2000);
           // Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "alert('aa')", true);

        }
        else
        {
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "myWindow.close();", true);
        }
    }


    catch (Exception rt)
    {
         Response.Write(rt.Message);
    }
}

我正在研究这个解决方案,但我不确定如何在我的代码中实现它。

Unable to evaluate expression... on web page

更新:

我实际上希望用户下载文件并使用脚本后面的代码关闭相同的代码,这些代码现在在代码中注释。

所以我不确定如何更好地优化这段代码来处理 response.end 语句生成的异常。

我尝试使用Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "myWindow.close();", true);,但它也不起作用。

谢谢

【问题讨论】:

    标签: c# asp.net webforms


    【解决方案1】:

    另一个答案似乎是说您可以不使用 Response.End 因为它是不必要的,或者为 ThreadAbortException 添加一个捕获,你有你当前的捕获

    问题链接到another question,建议添加以下内容:

    // Sends the response buffer
    Response.Flush()
    
    // Prevents any other content from being sent to the browser
    Response.SuppressContent = TrueResponse.SuppressContent = True
    

    【讨论】:

    • 我认为更好的方法是使用用户建议的建议并为此使用 .ashx 文件,然后我不需要关闭窗口。对于任何异常错误,我会将它们重定向到错误页面。
    【解决方案2】:

    使用HttpContext.Current.ApplicationInstance.CompleteRequest

    或尝试类似的东西

    Response.OutputStream.Flush()
    Response.OutputStream.Close()
    Response.Flush()
    Response.End() 
    

    阅读Is Response.End() considered harmful?

    【讨论】:

    • 我认为更好的方法是使用用户建议的建议并为此使用 .ashx 文件,然后我不需要关闭窗口。对于任何异常错误,我会将它们重定向到错误页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2019-03-01
    • 2023-02-10
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多