下载文件时报错 "由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值" 解决方法
下载文件的代码
/// <summary>
/// 下载文件操作类
/// </summary>
public static class DownLoadFiles
{
/// <summary>
/// 下载文件
/// </summary>
/// <param name="strDownLoadFileName">要下载的文件名称</param>
/// <returns></returns>
public static void DownLoadFile(string strDownLoadFileName)
{
if (String.IsNullOrEmpty(strDownLoadFileName))return;
try
{
FileInfo info = new FileInfo(strDownLoadFileName);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(info.Name));
HttpContext.Current.Response.AddHeader("Content-Length", info.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";//ms-excel
HttpContext.Current.Response.WriteFile(info.FullName);
//HttpContext.Current.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
throw ex;
}
}
}
// 最初是 HttpContext.Current.Response.End() 总是报错,异常“由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值”后来将上面的"HttpContext.Current.Response.End();"改成"HttpContext.Current.ApplicationInstance.CompleteRequest();",这个问题就自然的解决了。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步