c# - 从页面方法加载文件

标签 c# asp.net asp.net-ajax pagemethods

我有一个调用页面方法的 JavaScript 函数,如下所示:

function openFile(file) {
    PageMethods.LoadFile(file);
}

[System.Web.Services.WebMethod]
public static void LoadFile(string fileName)
{
   HttpContext.Current.Response.ClearContent();
   HttpContext.Current.Response.Buffer = true;
   HttpContext.Current.Response.ContentType = "application/binary";
   var filePath = @"C:\MyFiles\" + fileName;
   HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", fileName));
   HttpContext.Current.Response.WriteFile(filePath);
    HttpContext.Current.Response.End();
}

页面方法抛出以下异常:

Microsoft JScript 运行时错误:Sys.Net.WebServiceFailedException:服务器方法“LoadFile”失败,出现以下错误:System.Threading.ThreadAbortException-- 线程正在中止。

我该如何解决这个问题?

最佳答案

你得到这个异常是因为你调用了 End() 并强制中止。

HttpContext.Current.Response.End();

只需删除它。

引用:http://support.microsoft.com/kb/312629/
如果你用谷歌搜索:HttpContext.Current.Response.End

更新

我现在看到您尝试发送一个文件,但是您已经设置了本地磁盘的路径。将其更改为您的 http 地址。

关于c# - 从页面方法加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4372212/

相关文章:

c# - WPF 由祖传属性触发

c# - naudio 从麦克风录制声音然后保存

c# - session 变量在不同浏览器之间共享吗?

c# - 项目中不存在目标 "GetCopyToPublishDirectoryItems"。

c# - asp.net 添加 ApiController 作为依赖注入(inject)服务

c# - 像谷歌地方一样切换按钮

c# - 如何找到哪些 nuget 包包含我想要的项目

javascript - 当在文本框中搜索关键字时,我将之前的结果作为输出

asp.net - 如何重新定位 asp.net ajax ValidatorCalloutExtender

c# - 将字符串解析为动态类型的最快、高效、优雅的方式?