Web API控制器下载csv,但不能与jQuery一起工作

Web API controller downloads csv but doesn't work with jQuery

本文关键字:jQuery 一起 工作 但不能 API 控制器 下载 csv Web      更新时间:2023-09-26

我有一个简单的web api控制器,我可以通过url导航,它将下载。csv文件。现在我试图写一些jQuery,如果你点击按钮,它会下载它,但我错过了一些东西。

public HttpStatusCode Get(string id)
{
    var reportString = AskWebBusiness.Reports.GenerationQuestionReport(id);
    var response = HttpContext.Current.Response;
    response.ContentType = "text/csv";
    response.AppendHeader("Content-Disposition", "attachment;filename=" + "Questions Report.csv");
    response.Write(reportString);
    return HttpStatusCode.OK;
}

这段代码肯定可以工作,我可以去URL提示下载。

$('.js-btn-download-content').click(function (event) {
        var currentLanguage = getCulture();
        var url = baseUrl + 'report/get/' + currentLanguage;
        event.preventDefault();
        $('.loadingContent-download').fadeIn(200);
        $.ajax({
            headers: { 
                Accept : "text/csv; charset=utf-8",
                "Content-Type": "text/csv; charset=utf-8"
            },
            url: url,
            dataType: "text/csv",
            success: function (data) {
                $('.loadingContent-download').fadeOut(200);
                // Not sure about code below
                //var xmlDoc = $.parseXML(data);
                //var $xml = $(xmlDoc);
                //var $title = $xml.find("200");
                //if ($title) {
                    //$('.contentDownloaded-download p').html('Content donwloaded!');
                    //$('.contentDownloaded-download').show();
                //} else {
                    //$('.contentDownloaded-download p').html('Download failed! Please try again.');
                    //$('.contentDownloaded-download').show();
                //
            }
        });
        $('.js-btn-confirm').click(function () {
            $('.contentDownloaded-download').fadeOut(200);
        });
    });

正如你所看到的,这里是一些javaScript,我一直在应用程序中使用来处理一个OK被返回。但是,当该脚本触发时,浏览器不会下载该文件。什么好主意吗?

在你的Get(string id)方法中,返回HttpResponseMessage而不仅仅是HttpStatusCode。此外,ASP.net Web API不能确保HttpContext.Current.Response的状态(如果没有一些向导代码)。您可以这样做,将签名更改为Get(HttpRequestMessage request, string id),然后调用request。连接CreateResponse (statusCode、数据)。