【问题标题】:serve CSV file from web service call从 Web 服务调用中提供 CSV 文件
【发布时间】:2014-02-05 13:45:42
【问题描述】:

使用代码如:

    HttpContext.Current.Response.Clear()
    HttpContext.Current.Response.Buffer = True
    HttpContext.Current.Response.ContentType = "application/CSV"
    HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=FileName.csv")
    HttpContext.Current.Response.Charset = ""
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
    HttpContext.Current.Response.Write(csvString.ToString())
    HttpContext.Current.Response.[End]()

我可以通过网络服务调用提供 CSV 文件吗?它似乎不起作用我错过了什么?

我已经设置了一个传统的asp:button,它可以正确地提供文件,尽管 Web 服务返回一个 500 服务器错误Thread was being aborted

【问题讨论】:

  • 如果我没记错的话,应该是 text/CSV

标签: .net web-services csv export-to-csv


【解决方案1】:

您可以为文件返回一个字节数组。阅读Accept and Return file to/from C# WebService

话虽如此,但这是个人喜好,我喜欢保持我的 Web 服务“干净”,因为它们只返回 XML。毕竟,它们是用于机器间通信的,文件传输在 FTP 中有自己的协议,所以就是这样。就我而言,您正在寻找的行为应该被隔离到一个通用(ashx)处理程序中,该处理程序可以在需要时调用。再说一遍,这就是味道。

ashx 处理程序的摘录可能如下所示:

context.Response.ContentType = "text/CSV";
context.Response.AddHeader("Content-disposition", "attachment; filename=\"" 
   + fileName +  "\"");
context.Response.Clear();
context.Response.BinaryWrite(fileBytes);
context.Response.Flush();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2010-10-22
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多