How to Build a Dynamic Report Builder in ASP.NET Core 10 Using SQL Server and C# (2026)
A dynamic report builder in ASP.NET Core can let users choose dimensions, measures, date filters and sorting from an approved catalog. Map each choice to a fixed SQL expression and pass values as typed parameters. The result is a flexible reporting API with clear limits on which data and queries it can expose.
How does a configurable report stay safe?
The sales template offers region or category as the dimension, revenue or order count as the metric, and label or metric sorting. A dimension is the field used to group records. A measure is an aggregate over each group. Each fixture row represents an order. If production data has multiple rows per order, use a fact grain that matches your metric or explicitly count distinct orders.
| Request choice | Translation |
|---|---|
| dimension=region | Group by Region |
| metric=revenue | Sum Amount in each group |
| sort=metric | Sort descending by aggregate with a label tie-breaker |
| from and to | Bind typed date parameters with an exclusive end |
SQL parameterization protects values in WHERE clauses. An identifier such as Region cannot be passed as a parameter in GROUP BY. This implementation chooses from trusted code literals for each identifier and expression. It rejects arbitrary input before it constructs any command. This is also a useful boundary for maintaining predictable query plans.
Set up the sample
Use .NET 10, a SQL Server database and the SQL client package in the project. Run the seed script in an empty development database. Use a read-only login for the reporting application, and set ConnectionStrings__Reports in local secrets or environment configuration. Configure an authenticated test user in the Analyst role. The app provides a metadata endpoint and an execution endpoint.
The date filter is sargable because it compares the stored date directly with typed bounds. Return up to 200 groups. Fetching one extra group lets the endpoint detect overflow and require narrower criteria. The date range and query timeout also limit work. TOP does not prevent SQL Server from processing a large set before it groups and sorts. Evaluate actual plans with representative data.
Run and verify a report
Start on http://localhost:5092 in Development. For local JWT testing, run dotnet user-jwts create --name analyst --role Analyst --output token with the correct audience for this URL. Authenticate to GET /reports/templates/sales and verify the fields offered by the catalog. Then run this request using the resulting bearer token.
Calculate expected sums from the fixture before reading the response. West should total 20.50 and East should total 19.00. Test the same query with an unknown dimension and expect 400. An anonymous request should return 401 and an authenticated caller without Analyst should receive 403. Add download=true to test the JSON attachment. For large extracts, use a separately authorized background export pipeline with job limits and expiration.
Evolve templates and add tenant isolation
Use a template version when a dimension or metric changes meaning. Save the version and parameters of any report you need to reproduce. A saved definition alone cannot recreate historical results if the source data can change. Retain an export snapshot or query a dated fact model if the business requires repeatable history.
The sample models an Analyst role with access to all fixture rows. In a multi-tenant system, apply a trusted tenant filter before aggregation and include tenant scope in any cache key. Check access to the report template as well as the dataset. Avoid exposing group counts for populations the caller cannot see.
For a heavily used workload, index based on date filters and grouping, and benchmark selected candidate indexes on representative plans. Aggregate large datasets ahead of time when freshness requirements allow. Avoid SQL timeouts that exceed application or proxy deadlines. Monitor duration, row count, template version and failure rate, without logging sensitive filters.
Troubleshooting and FAQ
| Symptom | Where to look |
|---|---|
| Day-end records are missing | Confirm the requested end date is exclusive |
| Revenue differs from finance | Check currency, order grain, cancellations and rounding rules |
| Queries time out for one dimension | Inspect its cardinality, estimates and sort or aggregate spills |
| Users can see another customer’s totals | Enforce tenant scope before aggregation and test the cache key |
Can report authors paste raw SQL? This sample supports an approved dimension and measure catalog. A general-purpose SQL workspace would need a different permission model, isolation and resource controls.
Why export JSON? JSON keeps output typed and supports a simple bounded export. CSV and spreadsheets need separate rules for formula handling, data typing and streaming.
Read SQL Server GROUP BY, SQL Server index design, and the ASP.NET PB EF Core and SQL Server guide.
Comments
Post a Comment