gpt4 book ai didi

asp.net-core - .Net Core API 使用请求对象返回 StreamContent

转载 作者:行者123 更新时间:2023-12-02 20:20:14 27 4
gpt4 key购买 nike

我尝试从 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 不再使用 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

}

关于asp.net-core - .Net Core API 使用请求对象返回 StreamContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51596972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com