You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Minimal API响应GET请求发送文件?解决相关报错

通过Minimal API响应GET请求返回文件的正确实现

推荐最简方案:使用Results.File方法

这是Minimal API官方推荐的方式,无需手动处理流和响应头,框架会自动完成资源管理,代码简洁且不易出错:

Dim sPath As String = "E:\Users\Work\Desktop\20230208_220916.jpg"
oApp.MapGet("/download", Function()
                             Return Results.File(
                                 filePath:=sPath,
                                 contentType:="application/octet-stream",
                                 fileDownloadName:=Path.GetFileName(sPath)
                             )
                         End Function)

你之前代码的问题分析

第一个代码片段的错误

  1. 使用Sub作为处理委托,但内部调用异步方法CopyToAsync未加Await,导致文件流还未完成复制就结束了响应;同时框架因异步流程处理不当,误判存在请求体,触发Body was inferred but the method does not allow inferred body parameters错误。
  2. 修复后的手动流处理异步代码:
Dim sPath As String = "E:\Users\Work\Desktop\20230208_220916.jpg"
oApp.MapGet("/download", Async Function(Context)
                             Context.Response.ContentType = "application/octet-stream"
                             Context.Response.Headers.Add("Content-Disposition", $"attachment; filename={Path.GetFileName(sPath)}")
                             Context.Response.StatusCode = StatusCodes.Status200OK

                             Using oStream = File.OpenRead(sPath)
                                 Await oStream.CopyToAsync(Context.Response.Body)
                             End Using
                         End Function)

关键修改:改用Async Function并通过Await等待异步操作,让框架正确处理异步生命周期。

第二个代码片段的错误

使用Using包裹FileStream会导致返回FileStreamResult时,流已被Using语句释放,框架无法读取文件内容。修复方式是去掉Using,让框架负责流的释放:

Dim sPath As String = "E:\Users\Work\Desktop\20230208_220916.jpg"
oApp.MapGet("/download", Function(Context)
                             Dim oStream As New FileStream(sPath, FileMode.Open)
                             Return New FileStreamResult(oStream, "application/octet-stream") With {
                                 .FileDownloadName = Path.GetFileName(sPath)
                             }
                         End Function)

内容的提问来源于stack exchange,提问作者InteXX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:52:09