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

使用AspNetCore.Reporting的API控制器重复调用报FormatException错误

问题解决方案

错误原因

AspNetCore.Reporting生成PDF时会创建临时错误日志文件(如hdsktzjh.err),当前代码中LocalReport实例未被正确释放,导致后续请求无法访问该文件;同时未清理的资源会引发报表定义加载异常。

修复步骤

  1. 用using语句管理LocalReport生命周期:LocalReport实现了IDisposable接口,using会自动调用Dispose()释放文件锁和临时资源,彻底避免文件占用问题。
  2. 移除无用代码:原代码中MemoryStream变量未被使用,直接删除减少冗余。
  3. 简化参数逻辑:无需为每个报表单独创建字典,根据procedureRangeId动态生成参数即可,减少重复代码。

修改后的代码

using AspNetCore.Reporting;
using Microsoft.AspNetCore.Mvc;
using System.Net;

[HttpGet, Route("ProcedureRangeForm")]
public IActionResult ProcedureRangeForm(string procedureRangeId, byte procedureTypeId)
{
    int extension = 1;
    var _reportPath = "";
    switch (procedureRangeId)
    {
        case "1":
            _reportPath = @"Reports\ProcedureRangeForm1.rdlc";
            break;
        case "2":
            _reportPath = @"Reports\ProcedureRangeForm2.rdlc";
            break;
        case "3":
            _reportPath = @"Reports\ProcedureRangeForm3.rdlc";
            break;
        default:
            return BadRequest("无效的procedureRangeId");
    }

    var procedureType = _context.ProcedureTypes.FirstOrDefault(x => x.Id == procedureTypeId);
    if (procedureType == null)
    {
        return NotFound("未找到对应的ProcedureType");
    }

    // 动态生成报表参数
    var reportParams = new Dictionary<string, string>();
    if (procedureRangeId == "1")
    {
        reportParams.Add("UnitCode", "UnitCode");
    }
    reportParams.Add("ProcedureType", procedureType.Name!);

    // 使用using确保LocalReport资源自动释放
    using var localReport = new LocalReport(_reportPath);
    try
    {
        ReportResult result = localReport.Execute(RenderType.Pdf, extension, parameters: reportParams);
        byte[] file = result.MainStream;
        return new FileContentResult(file, "application/pdf");
    }
    catch (Exception e)
    {
        Console.WriteLine("{0} Exception caught.", e);
        return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
    }
}

额外建议

  • 确保Reports目录下的.rdlc文件路径正确,且应用程序对该目录有读写权限。
  • 高并发场景下,可配置独立临时文件目录避免冲突:
    // 在创建LocalReport前设置临时目录
    var tempDir = Path.Combine(Directory.GetCurrentDirectory(), "ReportTemp");
    Directory.CreateDirectory(tempDir);
    LocalReport.DefaultRenderingParameters.TempDirectory = tempDir;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:30:21