首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在swagger中下载文件?

如何在swagger中下载文件?
EN

Stack Overflow用户
提问于 2022-02-09 09:15:07
回答 1查看 1.7K关注 0票数 0

我需要在swagger中生成一个链接来下载文件,但是没有一个解决方案对我有效,请看我的代码-

“”“

代码语言:javascript
运行
复制
[HttpGet]
/// <response code="200">success</response>
[SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
[Route("api/Controller/DownloadFile")]
public ActionResult DownloadFile(string fileName)
        {
            try
            {
                var bytes = System.IO.File.ReadAllBytesAsync("\\\\test-dm.com\\testfile\\" + fileName);
                return PhysicalFile("application/pdf", Path.GetFileName("\\\\test-dm.com\\testfile\\" + fileName));
            }
            catch (Exception ex)
            {
                var bytes = new byte[0];
                return File("text/plain", "test.pdf"); ;
            }
        }

“”“

看看我的创业公司-

代码语言:javascript
运行
复制
services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "M2PPortal", Version = "v1" });
                
            });

在这里输入图像描述

见图1:https://i.stack.imgur.com/VwcG1.jpg

我只看到其他有下载文件链接的地方,我应该如何配置它。

这是我在这里的第一个问题,如果我的查询中有任何问题或需要任何其他信息,请告诉我。

EN

回答 1

Stack Overflow用户

发布于 2022-02-11 07:04:04

使用以下代码的见结果图像,如预期的那样给出了预期的结果,基本上是指向文件的链接-

代码语言:javascript
运行
复制
 [HttpGet]
        /// <response code="200">success</response>
        [SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
        [Route("api/Controller/DownloadFile")]
        public FileContentResult DownloadFile(string fileName)
        {
            try
            {
                return File(System.IO.File.ReadAllBytes(_configuration.GetValue<string>("FilePath:PathofFiles") + fileName), "application/pdf", fileName);
            }
            catch (Exception ex)
            {
               // write a generic return value which could be used to handle error
            }
        }

使用FileContentResult而不是操作或ActionResult或HttpResponseMessage。在配置或配置中不需要更改

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71046787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档