0

我让用户使用以下代码下载文件。它工作正常,但也会产生错误,错误的来源是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);
    }
}

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

无法评估表达式...在网页上

更新:

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

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

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

谢谢

4

2 回答 2

1

利用HttpContext.Current.ApplicationInstance.CompleteRequest

或尝试类似的东西

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

阅读Response.End() 被认为是有害的吗?

于 2013-10-06T07:46:09.730 回答
1

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

该问题链接到 另一个建议添加以下内容的问题:

// Sends the response buffer
Response.Flush()

// Prevents any other content from being sent to the browser
Response.SuppressContent = TrueResponse.SuppressContent = True
于 2013-10-06T07:40:03.413 回答