c# - 如何使用 jQuery Ajax 调用从 ASP.NET Web Api 下载 CSV 文件

标签 c# jquery asp.net-web-api

我正在研究如何通过 jQuery ajax 调用从 ASP.NET Web Api 下载 CSV 文件。 CSV 文件是根据自定义 CsvFormatter 从 Web API 服务器动态生成的。

来自 jQuery 的 Ajax:

   $.ajax({
        type: "GET",
        headers: {
            Accept: "text/csv; charset=utf-8",
        },
        url: "/api/employees",
        success: function (data) {
        }
    });

在服务器上,EmployeeCsvFormatter 的实现类似于下面的文章,派生自 BufferedMediaTypeFormatter:

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

public class EmployeeCsvFormatter : BufferedMediaTypeFormatter
{
    public EmployeeCsvFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
    }
    ...
}

我还添加了覆盖方法来表明我想像正常下载文件一样下载(可以在下载选项卡中看到下载文件):

 public override void SetDefaultContentHeaders(Type type, 
    HttpContentHeaders headers, MediaTypeHeaderValue mediaType)       
{
    base.SetDefaultContentHeaders(type, headers, mediaType);
    headers.Add("Content-Disposition", "attachment; filename=yourname.csv");
    headers.ContentType =  new MediaTypeHeaderValue("application/octet-stream");
}

但它不起作用,下载文件没有显示在状态栏或 Chrome 的下载选项卡中,即使来自 Fiddler,我看到它的响应似乎是正确的:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Mon, 11 Mar 2013 08:19:35 GMT
X-AspNet-Version: 4.0.30319
Content-Disposition: attachment; filename=yourname.csv
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/octet-stream
Content-Length: 26
Connection: Close

1,Cuong,123
1,Trung,123

我在 ApiController 中的方法:

public EmployeeDto[] Get()
{
    var result = new[]
               {
                   new EmployeeDto() {Id = 1, Name = "Cuong", Address = "123"},
                   new EmployeeDto() {Id = 1, Name = "Trung", Address = "123"},
               };

    return result;
}

一定是哪里错了,我还没弄清楚。如何像正常方式一样通过下载 CSV 文件使其工作?

最佳答案

jQuery Plugin for Requesting Ajax-like File Downloads不用 Ajax 就可以吗 using a simple form submit .

内部:

jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
    .appendTo('body').submit().remove()

它有一个 ajax 风格的接口(interface),所以从外部你可以这样调用它

$.download('/api/employees','format=csv');

另一种简单的方法使用:

$('#btnDownload').click(function (e) {
    e.preventDefault();
    window.location = "/api/employees?format=csv";
});

在服务器上,MediaTypeMappings 必须通过添加一个构造函数来使用:

    public EmployeeCsvFormatter(MediaTypeMapping mediaTypeMapping)
        : this()
    {
        MediaTypeMappings.Add(mediaTypeMapping);
    }

然后,将此格式化程序添加到 Web Api 配置中:

   configuration.Formatters.Add(new EmployeeCsvFormatter
            (new QueryStringMapping("format", "csv", "text/csv")));

关于c# - 如何使用 jQuery Ajax 调用从 ASP.NET Web Api 下载 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15334227/

相关文章:

C# 运算符重载 ==

javascript - JQuery 动态创建可编辑文本的可拖动 Div

c# - 使用 PerRequestLifetimeManager() 配置的 Unity 针对 WebApi 请求而非 MVC 请求创建多个 DbContext 实例

angularjs - 在 Web API 2 中如何接受简单类型作为 post 参数以及 Route 参数

Azure 请求的资源上不存在 'Access-Control-Allow-Origin' header

c# - 如何从下拉列表中管理 GridView 中显示的内容?

c# - Windows 和 IIS 7.5 上的匿名身份验证,允许内部自动登录和外部手动登录

c# - 返回带有 Ajax 的 PartialView 未在页面上插入

javascript - 为什么 JQuery 脚本不删除表行

java - 休息 Controller 工作,但 ajax post 方法返回错误