ASP.net WebAPI通过ajax调用返回文件

The*_*ads 5 c# ajax asp.net-mvc asp.net-web-api

我目前正在寻找一种方法来强制下载通过 WebAPI 控制器返回的文件。

我使用http://www.shawnmclean.com/blog/2012/04/force-download-of-file-from-asp-net-webapi/作为参考。

在我的客户端上,我使用 ajax GET 调用来发送对象的 ID 并尝试下载文件

    exportList: (foo, callback) =>
        path = '/api/export/id'
        path = path.replace("id", foo.id)
        $.ajax(
            url: path,
            dataType: 'text',
            success: (data) =>
                callback(data)
            error: (data) =>
                callback(false)
        )
Run Code Online (Sandbox Code Playgroud)

在服务器端,我将上面的 URI 路由到下面的方法

    [AcceptVerbs("GET")]
    public HttpResponseMessage ExportList(int id)
    {
        string file = fooService.ExportList(id);

        if (file == null)
        {
            return Request.CreateResponse(HttpStatusCode.NoContent);
        }
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StringContent(file);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "List.csv";

        return result;
    }
Run Code Online (Sandbox Code Playgroud)

fooService.ExportList 方法只是创建一个 csv 字符串。

当看到请求返回到客户端时,响应中确实包含 csv 字符串,但不会提示或强制客户端下载它。

这是解决这个问题的正确方法吗?

PcP*_*sar 3

我认为您使用 javascript 是因为动态 id 吗?如果您可以直接使用表单发布,则使用此类解决方案。如果确实需要 javascript,则使用这段代码来模拟表单操作:

$.download = function (url, data, method) {
    if (url && data) {
        //data can be string of parameters or array/object
        data = typeof data == 'string' ? data : jQuery.param(data).replace("\+", " ");
        data = data.replace(/\+/g, " ");
        var inputs = '';
        jQuery.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        //send request
        jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>')
        .appendTo('body').submit().remove();
    };
};
Run Code Online (Sandbox Code Playgroud)

调用下载的代码(而不是ajax调用):

path = '/api/export/id'
path = path.replace("id", foo.id)
$.download(path);
Run Code Online (Sandbox Code Playgroud)