.NET Core+Angular中Stimulsoft报表添加SQL连接字符串报错解决
Angular + .NET 5 环境下Stimulsoft Report Viewer SQL连接配置问题修复
问题概述
运行环境为Angular前端 + .NET 5(.NET Core)后端,使用Stimulsoft Report Viewer加载报表过程中,参照官方文档配置SQL连接字符串始终无法正常运行,存在两类异常:
- 执行强转代码
((StiSqlDatabase)report.Dictionary.Databases时抛出空引用异常 - 执行
report.Dictionary.Databases.Add(new StiSqlDatabase("ArchBD", "DataBaseConnectionString"));时抛出异常,提示初始化字符串格式不符合从索引0开始的规范
测试过的两种连接字符串均无法正常工作:
- 字符串
"Server=(localdb)\\mssqllocaldb; Database=MyDB; Trusted_Connection=True;"触发上述格式错误 - 字符串
"Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MyDB;Integrated Security=True;"抛出SQL连接建立失败的网络或实例相关错误
原有问题代码如下:
var report = new StiReport(); var path = StiAngularHelper.MapPath(this, $"{report}.mrt"); report.Load(path); var ConnectionString = ConnectionString; var conn = new Stimulsoft.Report.Dictionary.StiSqlDatabase("MyDb", ConnectionString); report.Dictionary.Databases.Add(conn);
修复步骤
按以下顺序调整即可解决全部问题:
- 修复空引用异常:加载未预置数据源的mrt报表文件时,
report.Dictionary对象不会自动初始化,直接访问其下的Databases集合必然触发空引用。在report.Load(path)执行后增加字典判空初始化逻辑:
不要直接对未判空的Databases集合执行强转、Add操作。if (report.Dictionary == null) { report.Dictionary = new Stimulsoft.Report.Dictionary.StiDictionary(); } - 修正路径生成逻辑:原有代码中
$"{report}.mrt"写法错误,直接对StiReport对象插值会返回对象类型名而非实际报表文件名,需替换为mrt文件的实际名称,例如"SalesReport.mrt"。 - 修复连接字符串格式错误:格式报错的核心原因是C#字符串转义处理不当。在代码中书写LocalDB连接串时,使用逐字字符串(字符串前加
@)即可,不需要对路径反斜杠做双写转义,同时不要使用DataBaseConnectionString这类无意义占位符,必须传入真实有效的连接串。正确的连接串写法示例:var connectionString = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=MyDB;Integrated Security=True;MultipleActiveResultSets=True"; - 修复LocalDB连接失败问题:LocalDB是用户级实例,IIS或dotnet进程默认运行身份没有对应实例的访问权限。将站点应用池的运行身份修改为已初始化过mssqllocaldb实例的本地Windows用户,同时在命令行执行
sqllocaldb start mssqllocaldb确保实例处于运行状态。 - 避免连接重名冲突:新增自定义连接前,先清空字典内预置的旧连接,防止同名键报错:
report.Dictionary.Databases.Clear();
最终可运行代码
var report = new StiReport(); // 替换为实际报表文件名 var reportPath = StiAngularHelper.MapPath(this, "MyReport.mrt"); report.Load(reportPath); // 初始化字典避免空引用 if (report.Dictionary == null) { report.Dictionary = new Stimulsoft.Report.Dictionary.StiDictionary(); } // 清空旧连接 report.Dictionary.Databases.Clear(); // 配置正确格式的连接串 var dbConnectionString = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=MyDB;Integrated Security=True;"; var dbConnection = new Stimulsoft.Report.Dictionary.StiSqlDatabase("MyDb", dbConnectionString); report.Dictionary.Databases.Add(dbConnection); // 后续执行报表渲染、返回Viewer结果的逻辑
内容的提问来源于stack exchange,提问作者Isaac Ikusika
相关产品推荐
相关产品推荐

