0

我正在尝试下载位于特定文件夹中的文件。我正在使用此代码,但它给了我一个错误Reponse.End();- > 无法评估表达式,因为代码已优化或本机框架位于调用堆栈的顶部

if (m.Path.EndsWith(".txt"))
            {
                Response.ContentType = "application/txt";
            }
            else if (m.Path.EndsWith(".pdf"))
            {
                Response.ContentType = "application/pdf";
            }
            else if (m.Path.EndsWith(".docx"))
            {
                Response.ContentType = "application/docx";
            }
            else
            {
                Response.ContentType = "image/jpg";
            }
            string nameFile = m.Path;

            Response.AppendHeader("Content-Disposition", "attachment;filename=" + nameFile);

            Response.TransmitFile(Server.MapPath(ConfigurationManager.AppSettings["IMAGESPATH"]) + nameFile);
            Response.End();

我也试过Response.Write,但它给了我同样的错误。

4

1 回答 1

1

Response.End将抛出 ThreadAbortException 并且它只是为了与旧 ASP 兼容而存在,您应该使用HttpApplication.CompleteRequest

这是示例:

public class Handler1 : IHttpHandler
{    
  public void ProcessRequest(HttpContext context)
  {
    context.Response.AppendHeader("Content-Disposition", "attachment;filename=pic.jpg");
    context.Response.ContentType = "image/jpg";
    context.Response.TransmitFile(context.Server.MapPath("/App_Data/pic.jpg"));
    context.ApplicationInstance.CompleteRequest();
  }

  public bool IsReusable
  {
    get
    {
      return false;
    }
  }
}
于 2013-09-30T11:52:24.123 回答