Recipe 11.6 · C#
RDLC and SSRS in Modern Apps
Problem
Many line-of-business systems have years of reports built as SSRS server reports or RDLC files rendered by the ReportViewer control in Web Forms or WinForms. When the application moves to ASP.NET Core, the ReportViewer web control does not come along, and rewriting fifty reports is not in anyone's budget.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath =
Server.MapPath("~/Reports/Invoice.rdlc");
ReportViewer1.LocalReport.DataSources.Add(
new ReportDataSource("InvoiceLines", GetLinesDataTable(id)));
ReportViewer1.LocalReport.Refresh();
This works in a Web Forms page on .NET Framework and nowhere else.
The improved recipe
There are two practical routes. For reports deployed to an SSRS (or Power BI Report Server) instance, call the server's URL access endpoint and stream the rendered file; that needs only HttpClient. For local RDLC files, the community package ReportViewerCore.NETCore ports the RDLC rendering engine to modern .NET and renders to PDF, Excel or Word on the server, without the viewer UI.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Export;
public sealed class SsrsReportClient
{
private readonly HttpClient _http;
// BaseAddress: e.g. http://localhost/ReportServer
public SsrsReportClient(HttpClient http)
{
ArgumentNullException.ThrowIfNull(http);
_http = http;
}
public async Task<byte[]> RenderAsync(
string reportPath,
string format,
IReadOnlyDictionary<string, string?> parameters,
CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(reportPath);
ArgumentException.ThrowIfNullOrWhiteSpace(format);
string path = string.Join("/", reportPath
.Split('/', StringSplitOptions.RemoveEmptyEntries)
.Select(Uri.EscapeDataString));
var url = new StringBuilder("?/").Append(path)
.Append("&rs:Command=Render&rs:Format=")
.Append(Uri.EscapeDataString(format));
foreach (var (name, value) in parameters)
{
url.Append('&').Append(Uri.EscapeDataString(name));
url.Append(value is null
? ":isnull=true"
: "=" + Uri.EscapeDataString(value));
}
using var response = await _http.GetAsync(url.ToString(), ct);
response.EnsureSuccessStatusCode();
string? type = response.Content.Headers.ContentType?.MediaType;
if (type is "text/html")
{
throw new InvalidOperationException(
$"SSRS returned an error page for {reportPath}.");
}
return await response.Content.ReadAsByteArrayAsync(ct);
}
}
And the local RDLC route. NuGet package: ReportViewerCore.NETCore.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Reporting.NETCore;
namespace ImproveCode.Export;
public static class RdlcRenderer
{
public static byte[] Render(
string rdlcPath,
string format,
IReadOnlyDictionary<string, object> dataSources,
IReadOnlyDictionary<string, string> parameters)
{
using var definition = File.OpenRead(rdlcPath);
var report = new LocalReport();
report.LoadReportDefinition(definition);
foreach (var (name, data) in dataSources)
{
report.DataSources.Add(new ReportDataSource(name, data));
}
var values = new List<ReportParameter>();
foreach (var (name, value) in parameters)
{
values.Add(new ReportParameter(name, value));
}
report.SetParameters(values);
return report.Render(format);
}
}
A usage snippet for registering the SSRS client with Windows authentication:
builder.Services.AddHttpClient<SsrsReportClient>(client =>
{
client.BaseAddress = new Uri("http://localhost/ReportServer");
client.Timeout = TimeSpan.FromMinutes(5);
})
.ConfigurePrimaryHttpMessageHandler(() =>
new HttpClientHandler { UseDefaultCredentials = true });
How it works
SSRS URL access has been part of Reporting Services since the beginning: a GET request to ReportServer?/Folder/Report&rs:Format=PDF with report parameters as query values returns the rendered file. The client escapes each path segment and parameter, and sends :isnull=true for null parameters, which is how SSRS expects them. Format names are SSRS's own: PDF, EXCELOPENXML, WORDOPENXML, CSV, IMAGE.
SSRS has a habit of returning an HTML error page with a success status when a parameter is wrong, so the client checks the content type and throws instead of handing a user an "Excel file" that is really HTML. The HttpClient comes from IHttpClientFactory (Chapter 13), with UseDefaultCredentials so the application pool or service account authenticates to the report server through Windows authentication. Grant that account the Browser role on the report folder and nothing more.
RdlcRenderer keeps existing .rdlc files working. LocalReport takes the definition, one ReportDataSource per dataset named in the report (the names must match), and the report parameters, then Render("PDF") returns the bytes. The data sources can be a DataTable or any IEnumerable of objects whose property names match the dataset fields, so a list of records from Dapper works.
Variations and pitfalls
- The package is unofficial.
ReportViewerCore.NETCoreis a community port, not a Microsoft product. Read its README for supported formats and platform limits, test every report you migrate, and treat it as a bridge while you move reports to SSRS or rewrite the important ones with QuestPDF. - No interactive viewer. Neither route gives you drill-down, sorting or paging in the browser. Most users just want the PDF or Excel file. For interactive reports, link to the SSRS web portal or Power BI.
- Timeouts. Big reports take minutes. Set the client timeout to match, and for anything slower, render in a background job (Chapter 14) and e-mail a link (Chapter 9).
- The REST API. SSRS 2017 and later also have a REST API at
/Reports/api/v2.0for managing catalog items and subscriptions. For rendering, URL access is still the simplest call.