AJAX 调用 WebAPI Get 方法的参数不下载文件 ASP .NET MVC

Posted

技术标签:

【中文标题】AJAX 调用 WebAPI Get 方法的参数不下载文件 ASP .NET MVC【英文标题】:AJAX call to WebAPI Get method with Parameters not downloading file ASP .NET MVC 【发布时间】:2020-04-07 06:31:14 【问题描述】:

我正在尝试从 WEB API Get 类型的 HttpResponseMessage 方法下载一个 excel 文件。 我可以通过 AJAX 调用来访问该方法,该方法还返回一个结果内容,但它没有在浏览器上下载文件。我试过window.location,它重定向到一个新页面,上面写着-'该网站无法显示该页面'。我尝试通过在成功和错误中发出警报来进行调试,它在错误中作为 [Object object] 发出警报。以下是我的代码,请纠正我哪里出错了。谢谢。

javascript

$(document).ready(function () 
    $("#btnDownload").click(function ()         
        var apiUrl = "../api/DownloadExcel/ExportExcelFile?OriginalRequestNumber=";
        var originalReqIdentifier = $('#OriginalRequestNumber').val();
        $.ajax(
            url: apiUrl + originalReqIdentifier,
            type: 'GET',
            dataType: 'json',
            success: function (data) 
                alert(data);
            ,
            error: function (data) 
                alert('hi');
            
        );
    );
);

html

<input href="#" class="btn" type="Submit" id="btnDownload" name="btnDownload" value="Download" />

c#

    public class DownloadExcelController : ApiController

    private IExcelExport _excelExport  get; set; 

    public DownloadExcelController()
    
        _excelExport = new GenerateExcel();
    
// GET api/DownloadExcel/ExportExcelFile
    [HttpGet]       
    public HttpResponseMessage ExportExcelFile(string OriginalRequestNumber)
    
        var ObjectToExcel = new List<DummyExternalLoginViewModel>
        
            new DummyExternalLoginViewModel  Name = "Mohammed", FamilyName= "Ansari", State = "CA",
            new DummyExternalLoginViewModel  Name = "Harvey", FamilyName= "Spectre", State = "NY",
            new DummyExternalLoginViewModel  Name = "Mike", FamilyName= "Ross", State = "NY",
            new DummyExternalLoginViewModel  Name = "Donald", FamilyName= "Trump", State = "AL",
            new DummyExternalLoginViewModel  Name = "Spencer", FamilyName= "Mike", State = "AK",
            new DummyExternalLoginViewModel  Name = "Trump", FamilyName= "Donald", State = "AZ",
            new DummyExternalLoginViewModel  Name = "Bill", FamilyName= "Gates", State = "AR"
        ;
        var resultContent = _excelExport.Export(ObjectToExcel, "ExcelExport", true);

        return resultContent;
      
 

【问题讨论】:

【参考方案1】:

您在双方都有问题 - 客户端和服务器问题:

使用同步文件下载(或如Download a file by jQuery.Ajax 所述的异步):

$(document).ready(function () 
    $("#btnDownload").click(function ()         
        var apiUrl = "../api/DownloadExcel/ExportExcelFile?OriginalRequestNumber=";
        var originalReqIdentifier = $('#OriginalRequestNumber').val();

        window.location = apiUrl + originalReqIdentifier;
    );
);

定义HttpResponseMessage所需的属性:

[HttpGet]       
public HttpResponseMessage ExportExcelFile(string OriginalRequestNumber)

    // ..
    var resultContent = _excelExport.Export(ObjectToExcel, "ExcelExport", true);

    var stream = new MemoryStream(resultContent);

    var response = new HttpResponseMessage(HttpStatusCode.OK)  Content = new StreamContent(stream) ;

    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")  FileName = "file.xlsx" ;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");

    return response;
 

【讨论】:

这些响应行已在 Export 方法中定义。新窗口打开时出现错误 - 此错误(HTTP 405 Method Not Allowed)表示 Internet Explorer 能够连接到该网站,但该网站存在编程错误。 请在浏览器检查时查看附加的错误图像【参考方案2】:
<script>
$(document).ready(function () 
    $("#btnDownload").click(function ()         
        var apiUrl = "../api/DownloadExcel/ExportExcelFile?OriginalRequestNumber=";
        var originalReqIdentifier = $('#OriginalRequestNumber').val();          
        $.ajax(
            url: apiUrl + originalReqIdentifier,
            type: 'GET',
            dataType: 'json',
            success: function (data) 
                alert(data);
            ,
            error: function (data) 
                window.location = apiUrl + originalReqIdentifier;
            
        );
    );
);
</script>

放置 window.location = apiUrl + originalReqIdentifier;在 Ajax 错误中,为我工作。

【讨论】:

以上是关于AJAX 调用 WebAPI Get 方法的参数不下载文件 ASP .NET MVC的主要内容,如果未能解决你的问题,请参考以下文章

使用 ajax 调用 webapi get 方法时出现 405 错误

.Net WebAPI+Jquery Ajax 请求参数

如何从 jQuery ajax 调用将复杂对象传递给 ASP.NET WebApi GET?

如何在WebAPI的控制器的GET请求中传递参数

js调用webapi如何传递日期类型参数

Web Api 参数始终为空