【问题标题】:.Net Core API Returning StreamContent with request object.Net Core API 返回带有请求对象的 StreamContent
【发布时间】:2019-01-06 21:09:25
【问题描述】:

我正在尝试从 Web API 返回一个 excel 文件,但我得到的是 JSON 响应而不是下载的文件。

using (var excel = new ExcelPackage())
        {
            var sheet = excel.Workbook.Worksheets.Add("Placments");

            var taxonomyConnStr = GetConnectionString(DatabaseSettings.ConnectionStringNames.Taxonomy);
            var plookConnStr = GetConnectionString(DatabaseSettings.ConnectionStringNames.Plook);
            var content = _repo.GetPlacementDataTable(masterAgencyDivisionId, masterClientId, plookConnStr);



            if (content.Rows.Count > 0)
            {
                Color colFromHex = System.Drawing.ColorTranslator.FromHtml("#000000");

                sheet.Row(1).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                sheet.Row(1).Style.Fill.BackgroundColor.SetColor(colFromHex);
                sheet.Row(1).Style.Font.Color.SetColor(Color.White);
                sheet.Row(1).Style.Font.Bold = true;
                sheet.Row(1).Style.Font.Size = 12;

                sheet.Cells[1, 1].LoadFromDataTable(content, true);

                sheet.Cells[sheet.Dimension.Address].AutoFitColumns();

            }
            else
            {
                sheet.Cells[1, 1].LoadFromText("There is no data for filtered results. Please adjust your selections.");
            }

            var stream = new MemoryStream();
            excel.SaveAs(stream);
            stream.Position = 0;

            var result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-sream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Report.xlsx"

            };

            return result;

        }

这是我的 AJAX 调用

$(document).ready(function () {
    $("#btnSubmit").click(function () {
           window.location = "https://localhost:44318/custom/GetPlacementExcel/6/77";
           })
})

但我得到的回应是:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1}, "content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=Report.xlsx"]},{"key":"Content-Type"," value":["application/octet-stream"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

【问题讨论】:

    标签: asp.net-core asp.net-core-2.0 asp.net-core-webapi


    【解决方案1】:

    Asp.Net Core 不再使用HttpResponseMessage,因此您需要使用适当的操作结果来返回所需的数据。

    由于您已经将数据存储在流中,因此返回 FileStreamResult 以及正确的矿类型和文件名应该可以满足您的需求。

    public IActionResult MyAction() {
    
        //...code removed for brevity
    
        var stream = new MemoryStream();
        excel.SaveAs(stream);
        stream.Position = 0;
        var fileName = "Report.xlsx";
        var mimeType = "application/vnd.ms-excel";
        //return the data stream as a file
        return File(stream, mimeType, fileName); //<-- returns a FileStreamResult
    
    }
    

    【讨论】:

    • 次要,但 MIME 类型应为 application/vnd.ms-excel
    • @MarkG 我只是把他们在原始代码中的内容。可以轻松更新它。 :P
    猜你喜欢
    • 2018-04-28
    • 1970-01-01
    • 2021-12-18
    • 2021-11-18
    • 1970-01-01
    • 2020-05-02
    • 2021-11-08
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多