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

ASP.NET 7.0中return File()返回图片时HTTPS连接无法关闭的问题

补充说明

经过进一步研究发现,仅在使用HTTPS时会出现此问题,使用HTTP时连接会按预期关闭。我已尝试多款浏览器,表现均一致;也测试了curl和wget,它们能下载图片并结束进程,但使用curl的--trace参数时,跟踪信息末尾会显示:

== Info: Connection #0 to host localhost left intact

我目前在ASP.NET 7.0中引入System.Windows.Forms.DataVisualization.Charting库重写应用的旧模块,需要将图表渲染结果返回给浏览器。我的控制器方法如下:

public IActionResult Graph(int id)
{
    var ant = RandomNumberGenerator.GetInt32(3, 7);
    using var testGraph = new MyCustomChart(85, true);
    for (int i = 0; i < ant; i++)
    {
        testGraph.AddUnit(i, $"Unit {i}", RandomNumberGenerator.GetInt32(0,101)); 
    }
    var bytes = testGraph.Render(0, 0, ChartImageFormat.Png);
    return File(bytes, "image/png");
}

该方法会生成包含3到6个柱状条的图表,数值范围为0到100。MyCustomChart是基于原生库的封装类,仅在调用.Render()方法时才会执行相关操作。.Render()方法包含3个参数,目前仅使用ChartImageFormat参数,另外两个宽高参数在测试中被硬编码。以下是省略图表构建逻辑后的.Render()方法:

public byte[] Render(int width, int height, ChartImageFormat fmt)
{
  using var chart = new Chart();
  Chart.Size = new Size(1024, enheter.Count * 100);

  // 省略大量图表构建代码

  using MemoryStream imageStream = new MemoryStream();
  Chart.SaveImage(imageStream, ChartImageFormat.Png);
  return imageStream.ToArray();
}

我尝试过在Chart()实例中使用和不使用using语句,结果一致。

当前出现的问题:

  • 将该端点用于<img>标签时,图表能正常显示,但浏览器会持续加载;在Chrome中点击停止加载后,图表会消失并替换为“图片无法找到”的占位图。
  • 直接访问该端点时,图表能正常显示,但浏览器始终处于加载状态。

我使用dotnet run运行应用,没有报错日志,同时也没有记录对Graph()端点的请求,这可能是返回File数据的默认行为?

有人知道这是什么原因吗?

我附上了展示问题的GIF动图……看不到我的光标,但我一直在点击刷新和停止按钮。
问题录屏

内容的提问来源于stack exchange,提问作者Christian Wattengård

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:37:17