简体   繁体   English

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

[英]AJAX call to WebAPI Get method with Parameters not downloading file ASP .NET MVC

405错误 I am trying to download an excel file from WEB API Get method of type HttpResponseMessage.我正在尝试从 HttpResponseMessage 类型的 WEB API Get 方法下载一个 excel 文件。 I am able to hit the method by making an AJAX call, the method also returns a resultcontent, but it's not downloading the file on the browser.我可以通过进行 AJAX 调用来调用该方法,该方法还返回结果内容,但它不会在浏览器上下载文件。 I tried window.location, it redirects to a new page saying - 'The website cannot display the page' .我试过 window.location,它重定向到一个新页面说 - 'The website cannot display the page' I tried to debug by alerting in success & error, it alerts in error as [Object object].我尝试通过在成功和错误中发出警报来进行调试,它在错误中发出警报作为 [Object object]。 Below is my code, please correct where I am going wrong.下面是我的代码,请纠正我哪里出错了。 Thanks.谢谢。

JavaScript 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 HTML

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

c# 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;
    }  
 }

You have issues on both sides - client & server ones:您在双方都有问题 - 客户端和服务器:

Use sync file download (or async as described Download a file by jQuery.Ajax ):使用同步文件下载(或异步如所述通过 jQuery.Ajax 下载文件):

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

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

Define the required properties of HttpResponseMessage:定义 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;
} 
<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>

placing window.location = apiUrl + originalReqIdentifier;放置 window.location = apiUrl + originalReqIdentifier; in Ajax error, worked for me.在 Ajax 错误中,为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM