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

Asp.Net 6.0重定向JSON文件URL时如何触发浏览器自动下载?

解决JSON文件重定向后自动下载问题

问题原因

你之前的代码无效,是因为Response.Redirect会让浏览器发起新请求,此时你设置的Content-Disposition和ContentType会被托管服务器返回的响应头覆盖,浏览器最终依据托管服务器的头信息直接渲染JSON文件。

可行解决方案

方案1:前端JS自动触发下载(无需代理文件)

在MVC控制器返回临时视图,通过页面内JavaScript自动创建带download属性的链接并触发点击,实现自动下载。

控制器代码:

public IActionResult DownloadJson(string fileName)
{
    string fileUrl = "https://hostedfilelocation/....test.json";
    ViewBag.FileUrl = fileUrl;
    ViewBag.FileName = fileName;
    return View();
}

对应视图(DownloadJson.cshtml):

<!DOCTYPE html>
<html>
<head>
    <script>
        window.onload = function() {
            const downloadLink = document.createElement('a');
            downloadLink.href = '@ViewBag.FileUrl';
            downloadLink.download = '@ViewBag.FileName';
            document.body.appendChild(downloadLink);
            downloadLink.click();
            // 清理元素并关闭页面(可选)
            document.body.removeChild(downloadLink);
            window.close();
        };
    </script>
</head>
<body>
    <p>正在准备下载...</p>
</body>
</html>

方案2:流式代理文件(权衡带宽限制)

若前端方案不适用,可通过服务器流式代理文件,避免一次性加载整个文件到内存:

public async Task<IActionResult> DownloadJson(string fileName)
{
    string fileUrl = "https://hostedfilelocation/....test.json";
    
    using var httpClient = new HttpClient();
    var remoteResponse = await httpClient.GetAsync(fileUrl, HttpCompletionOption.ResponseHeadersRead);
    remoteResponse.EnsureSuccessStatusCode();
    
    var fileStream = await remoteResponse.Content.ReadAsStreamAsync();
    return File(fileStream, "application/octet-stream", fileName);
}

注:此方案会占用服务器带宽,但流式传输不会将完整文件加载到服务器内存,性能影响可控。

方案3:修改托管服务器响应头(若有权限)

如果能控制JSON托管服务器的配置,直接在托管端添加响应头:

  • Content-Type: application/octet-stream
  • Content-Disposition: attachment; filename="指定文件名.json"

这样浏览器访问该文件时会自动触发下载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:40:33