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

.NET 6 Web API实现PDF文件自动下载的方法咨询

实现.NET 6 Web API自动触发PDF文件下载

要让API调用时自动触发文件下载,核心是确保响应头的Content-Disposition被设置为attachment(强制下载),而非默认的inline(在线预览)。以下是两种可行的修改方案:

方案一:使用PhysicalFileResult(推荐)

PhysicalFileResult是ASP.NET Core提供的更简洁的文件返回类型,会自动处理文件流和响应头,同时支持断点续传。修改后的代码如下:

public async Task<IActionResult> GetGeneratedEReceipt(string fileName) 
{  
    try
    {
        string assetPath = "Pictures";
        string generatedFileName = $"{fileName}.pdf";
        string path = Path.Combine(assetPath, generatedFileName);

        if (!System.IO.File.Exists(path))
        {
            return NotFound("指定的PDF文件不存在");
        }

        // 第三个参数指定下载文件名,最后一个参数开启断点续传
        return PhysicalFile(path, "application/pdf", $"{fileName}.pdf", enableRangeProcessing: true);
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, $"下载失败:{ex.Message}");
    }
}

方案二:手动设置Content-Disposition响应头

如果要保留原有的FileStreamResult实现,可以手动添加响应头强制触发下载:

public async Task<FileStreamResult> GetGeneratedEReceipt(string fileName) 
{  
    FileStreamResult? fileOutput = null;
    try
    {
        string assetPath = "Pictures";
        string generatedFileName = $"{fileName}.pdf";
        string path = Path.Combine(assetPath, generatedFileName);

        if (System.IO.File.Exists(path))
        {
            var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
            fileOutput = new FileStreamResult(stream, "application/pdf") 
            { 
                FileDownloadName = $"{fileName}.pdf" 
            };
            // 强制设置响应头,确保浏览器自动触发下载
            Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}.pdf\"");
        }
        else
        {
            throw new FileNotFoundException("指定的PDF文件不存在");
        }
    }
    catch (Exception)
    {
        throw;
    }

    return fileOutput;
}

关键说明

  • Content-Disposition: attachment告诉浏览器将响应内容视为下载文件,而非在线预览资源,因此会自动触发本地下载流程。
  • 两种方案都修复了原代码中文件不存在时返回null导致的服务器错误问题,增加了更友好的错误反馈。
  • 如果下载文件名包含中文,建议对文件名进行URL编码(如HttpUtility.UrlEncode(fileName)),避免出现乱码问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:30:10