ASP.NET PB is a practical learning hub for ASP.NET Core, C#, .NET Web API, SQL Server, Entity Framework Core, and AI development. Explore step-by-step tutorials, real-world coding examples, debugging solutions, performance optimization, and deployment guides. Learn to build secure, scalable, modern applications with clear explanations, working code, and developer-friendly best practices.
How to Build a Dynamic Form Builder in ASP.NET Core 10 Using JSON Schema and SQL Server (2026)
A dynamic form builder in ASP.NET Core stores versioned JSON Schema in SQL Server, renders a supported subset in the browser, and validates submitted JSON against the exact stored version. A feedback form can require reproduction steps when its category is “bug” while keeping those steps out of general feedback. Old submissions retain the contract that accepted them.
How the form contract works
Load immutable schema version. Render supported controls. Validate on the server. Save payload and version.
Treat the schema and the UI as two components. JSON Schema describes valid data. The browser translates a small set of field definitions into controls and applies display rules. A full schema can express patterns, composition, or references that this browser does not implement. Keep the renderer’s supported vocabulary explicit and review every definition before publishing it.
Layer
Responsibility
Failure example
SQL Server
Keep immutable schema versions and submission receipts
Removing a version would orphan submitted data
Browser
Display controls and provide immediate feedback
A direct API request can bypass every browser check
ASP.NET Core
Authenticate, resolve the stored schema, validate and write
A valid payload for version 1 may fail under version 2
The sample accepts a category enum, a short text summary, and a conditional steps field. The if clause includes required so a missing discriminator does not count as a match. The then clause requires steps and the else clause forbids it. Set additionalProperties to false to reject unexpected fields. See JSON Schema conditionals.
Set up SQL Server and the project
Use the .NET 10 SDK and an empty SQL Server database. Run the script as a deployment identity. The API identity needs SELECT on FormVersion and INSERT on FormSubmission plus the permissions required by the OUTPUT clause. Keep schema authoring and migrations under a separate identity. Supply a trusted TLS connection string through ConnectionStrings__Forms or user secrets.
schema.sql
CREATE TABLE dbo.FormVersion (
FormId int NOT NULL, VersionNumber int NOT NULL,
SchemaJson nvarchar(max) NOT NULL CHECK (ISJSON(SchemaJson)=1),
PRIMARY KEY (FormId,VersionNumber)
);
CREATE TABLE dbo.FormSubmission (
Id bigint IDENTITY PRIMARY KEY, FormId int NOT NULL, VersionNumber int NOT NULL,
Subject nvarchar(128) NOT NULL, Payload nvarchar(max) NOT NULL CHECK (ISJSON(Payload)=1),
CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),
FOREIGN KEY (FormId,VersionNumber) REFERENCES dbo.FormVersion(FormId,VersionNumber)
);
INSERT dbo.FormVersion VALUES (1,1,N'{
"$schema":"https://json-schema.org/draft/2020-12/schema",
"type":"object","additionalProperties":false,
"properties":{
"category":{"type":"string","title":"Category","enum":["general","bug"]},
"summary":{"type":"string","title":"Summary","minLength":1,"maxLength":120},
"steps":{"type":"string","title":"Reproduction steps","minLength":1,"maxLength":500}
},
"required":["category","summary"],
"if":{"required":["category"],"properties":{"category":{"const":"bug"}}},
"then":{"required":["steps"]},
"else":{"not":{"required":["steps"]}}
}');
The foreign key preserves the relationship between a receipt and a particular schema. Publish a new row for version 2 when validation changes. Existing browser tabs continue posting version 1 while your product supports it. Add an explicit retirement policy when you need to close a version to new writes.
The handler obtains the subject from the authenticated principal. A caller cannot set it in the submitted JSON. Route values select the schema, typed parameters bind the database inputs, and the body cap limits work before parsing. A schema mismatch returns a generic client error. For a richer UI, map vetted validation locations to field messages without returning private definitions or raw payloads to telemetry.
Program.cs
using System.Data;
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Nodes;
using Json.Schema;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Data.SqlClient;
var b = WebApplication.CreateBuilder(args);
b.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 16_384);
b.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
b.Services.AddAuthorization();
var app = b.Build();
var connection = b.Configuration.GetConnectionString("Forms")
?? throw new InvalidOperationException("Configure ConnectionStrings__Forms.");
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapGet("/forms/{id:int}/versions/{version:int}", async (int id, int version, CancellationToken ct) =>
{
await using var db = new SqlConnection(connection);
await db.OpenAsync(ct);
var schema = await ReadSchema(db, id, version, ct);
return schema is null ? Results.NotFound() : Results.Text(schema, "application/schema+json");
}).RequireAuthorization();
app.MapPost("/forms/{id:int}/versions/{version:int}/submissions", async (
int id, int version, JsonElement body, ClaimsPrincipal user, CancellationToken ct) =>
{
var subject = user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub");
if (subject is not { Length: > 0 and <= 128 }) return Results.Forbid();
await using var db = new SqlConnection(connection);
await db.OpenAsync(ct);
var text = await ReadSchema(db, id, version, ct);
if (text is null) return Results.NotFound();
var schema = JsonSchema.FromText(text);
if (!schema.Evaluate(JsonNode.Parse(body.GetRawText())).IsValid)
return Results.BadRequest(new { error = "Submission does not match this version." });
await using var cmd = new SqlCommand("""
INSERT dbo.FormSubmission(FormId,VersionNumber,Subject,Payload)
OUTPUT INSERTED.Id VALUES(@id,@version,@subject,@payload)
""", db);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@version", SqlDbType.Int).Value = version;
cmd.Parameters.Add("@subject", SqlDbType.NVarChar, 128).Value = subject;
cmd.Parameters.Add("@payload", SqlDbType.NVarChar, -1).Value = body.GetRawText();
var receipt = await cmd.ExecuteScalarAsync(ct);
return Results.Ok(new { receipt });
}).RequireAuthorization();
app.Run();
static async Task<string?> ReadSchema(SqlConnection db, int id, int version, CancellationToken ct)
{
await using var cmd = new SqlCommand("""
SELECT SchemaJson FROM dbo.FormVersion WHERE FormId=@id AND VersionNumber=@version
""", db);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@version", SqlDbType.Int).Value = version;
return await cmd.ExecuteScalarAsync(ct) as string;
}
Treat schemas as trusted deployment inputs. If a future authoring interface accepts arbitrary schemas, isolate processing and enforce complexity budgets and a strict reference policy before evaluating them. Nested schemas and patterns can consume significant work even with a small request body. The sample uses local rules and no external references. See JsonSchema.Net documentation.
Render and submit the form
Put both assets under wwwroot. The UI creates controls via DOM methods and assigns display strings via textContent. Keep this pattern for untrusted field labels. A native maxLength or required flag improves the form experience. The server still verifies data for clients that omit the UI.
The bearer-token field makes the example easy to run against local JWT authentication. In a browser production app, use your organization’s authentication flow. With same-site cookie authentication, add CSRF protection to the mutation endpoint and remove the token field. Treat submitted content as untrusted when rendering it in any later admin view, exporting it, or forwarding it to another system.
Test versioning and validation
Start the sample on localhost with Development enabled. Initialize user secrets and use dotnet user-jwts create --name alice --output token from the project directory. Match the audience to the URL you use, for example http://localhost:5088, and open that same origin. Copy only the development token into the local lab.
Choose Bug, fill Summary, and leave Steps empty. Browser validation should block it. Send the same JSON directly with a bearer token to POST /forms/1/versions/1/submissions and expect 400.
Send {"category":"bug","summary":"Save fails","steps":"Open the settings screen"}. Expect 200 with a numeric receipt.
Change category to general and keep steps. Expect 400. Omit steps and submit again. Expect 200.
Use a nonexistent version and expect 404. Remove the bearer token and expect 401.
Inspect stored rows as the lab administrator. Verify the two accepted rows refer to the version that validated them and that the subject came from authentication.
Compile verification and SQL execution are separate checks. Use this matrix with your SQL Server instance to confirm end-to-end behavior, including the grant required to return INSERTED.Id.
Troubleshoot and deploy
Symptom
What to inspect
General submissions always fail
Check whether hidden inputs are still serialized
The browser posts version 2 after loading version 1
Persist the version with the rendered form
A schema is readable but writes fail
Check insert and OUTPUT permissions and the version foreign key
Duplicate receipts on retries
Introduce a per-subject idempotency key and unique constraint
Real systems often scope form visibility to tenant or owner. Apply that filter to the lookup and use the same tenant when inserting. Rate-limit writes, avoid logging sensitive form data, and plan retention and deletion independently of schema version history. Add integration tests for conditional rules and migration compatibility.
FAQ and further reading
Can the form schema be edited in place? Use a new immutable version when the meaning or validity of submitted fields changes.
Can I use any JSON Schema keyword in the browser? This renderer supports only the demonstrated field subset. Add renderer capabilities and tests alongside schema changes.
Should I store each answer in a separate column? JSON works well for changing schemas. Project stable fields into explicitly typed columns or a reporting model when queries need predictable indexes.
Comments
Post a Comment