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?

Authorize the reporting role. Resolve allowed dimensions. Bind date values as parameters. Return bounded results.
Authorize the reporting role. Resolve allowed dimensions. Bind date values as parameters. Return bounded results.

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.

schema.sql
CREATE TABLE dbo.SalesFact (
    Id bigint IDENTITY PRIMARY KEY,
    SaleDate date NOT NULL,
    Region nvarchar(60) NOT NULL,
    Category nvarchar(60) NOT NULL,
    Amount decimal(12,2) NOT NULL
);
CREATE INDEX IX_SalesFact_SaleDate ON dbo.SalesFact(SaleDate)
INCLUDE (Region,Category,Amount);
INSERT dbo.SalesFact (SaleDate,Region,Category,Amount) VALUES
('2026-11-01',N'West',N'Mugs',12.50),
('2026-11-02',N'West',N'Cables',8.00),
('2026-11-03',N'East',N'Mugs',19.00);
Sample.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="6.1.*" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.*" />
  </ItemGroup>
</Project>
Program.cs
using System.Data;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Data.SqlClient;

var b = WebApplication.CreateBuilder(args);
b.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
b.Services.AddAuthorization();
var app = b.Build();
var connection = b.Configuration.GetConnectionString("Reports")
    ?? throw new InvalidOperationException("Configure ConnectionStrings__Reports.");

app.MapGet("/reports/templates/sales", () =>
    Results.Ok(new { dimensions = new[] { "region", "category" },
        metrics = new[] { "revenue", "orders" }, sorts = new[] { "label", "metric" } }))
    .RequireAuthorization(p => p.RequireRole("Analyst"));

app.MapGet("/reports/sales", async (DateOnly from, DateOnly to, string dimension,
    string metric, string? sort, bool? download, CancellationToken ct) =>
{
    var groupSql = dimension switch { "region" => "Region", "category" => "Category", _ => null };
    var valueSql = metric switch { "orders" => "COUNT_BIG(*)", "revenue" => "SUM(Amount)", _ => null };
    var orderSql = sort switch { null or "metric" => "Metric DESC, Label ASC",
        "label" => "Label ASC", _ => null };
    if (groupSql is null || valueSql is null || orderSql is null ||
        to <= from || to.DayNumber - from.DayNumber > 93)
        return Results.BadRequest(new { error = "Invalid report fields or date range." });

    await using var db = new SqlConnection(connection);
    await db.OpenAsync(ct);
    await using var cmd = new SqlCommand($"""
        SELECT TOP (201) {groupSql} AS Label, CAST({valueSql} AS decimal(28,2)) AS Metric
        FROM dbo.SalesFact WHERE SaleDate >= @from AND SaleDate < @to
        GROUP BY {groupSql} ORDER BY {orderSql}
        """, db) { CommandTimeout = 8 };
    cmd.Parameters.Add("@from", SqlDbType.Date).Value = from.ToDateTime(TimeOnly.MinValue);
    cmd.Parameters.Add("@to", SqlDbType.Date).Value = to.ToDateTime(TimeOnly.MinValue);
    await using var rows = await cmd.ExecuteReaderAsync(ct);
    var report = new List<ReportRow>();
    while (await rows.ReadAsync(ct))
        report.Add(new ReportRow(rows.GetString(0), rows.GetDecimal(1)));

    if (report.Count > 200)
        return Results.UnprocessableEntity(new { error = "Too many groups. Narrow the date range." });
    return download == true
        ? Results.File(JsonSerializer.SerializeToUtf8Bytes(report, JsonSerializerOptions.Web),
            "application/json", "sales-report.json")
        : Results.Ok(report);
}).RequireAuthorization(p => p.RequireRole("Analyst"));
app.Run();

public sealed record ReportRow(string Label, decimal Metric);

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.

BASH
curl -i -H "Authorization: Bearer $TOKEN" \
  'http://localhost:5092/reports/sales?from=2026-11-01&to=2026-11-04&dimension=region&metric=revenue&sort=metric'

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