【问题标题】:Failed to load API definition when a function returns a file函数返回文件时加载 API 定义失败
【发布时间】:2023-03-29 22:54:01
【问题描述】:

我的 API 项目使用 ASP.NET Core (.NET5)。一切正常,Swagger 页面显示所有 API。现在,在控制器中,我想添加一个函数来导出 Excel 文件。控制器中的代码是这样的:

[HttpGet]
public IActionResult DownloadExcel()
{
    byte[] reportBytes;

    using (var package = _utils.CreateCommentPackage())
    {
        reportBytes = package.GetAsByteArray();
    }

    return File(reportBytes, XlsxContentType, 
        $"Comments-{DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.xlsx");
}

非常简单,但没有创建 Swagger 定义。当我打开 Swagger 页面时,我看到了

如果我删除此功能,Swagger 将再次工作。

【问题讨论】:

标签: asp.net-core swashbuckle.aspnetcore


【解决方案1】:

你需要添加一个路由,修改你的代码如下;

[HttpGet]
[Route("api/DownloadExcel")]
public IActionResult DownloadExcel()
{
    byte[] reportBytes;

    using (var package = _utils.CreateCommentPackage())
    {
        reportBytes = package.GetAsByteArray();
    }

    return File(reportBytes, XlsxContentType, 
        $"Comments-{DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.xlsx");
}

【讨论】:

    猜你喜欢
    • 2018-09-18
    • 2018-10-16
    • 2018-08-23
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多