This is the .NET code behind Integrate SurveyJS with ASP.NET Core, as an ASP.NET Core application you can run example by example: minimal API endpoints, Razor Pages and SQLite through Entity Framework Core. Each example of that page has a page here that runs the real SurveyJS component against these endpoints, with a short "Try this" list, a live request log, a "What the server stored" panel and the code that just ran. SurveyJS has no backend of its own, so treat these as starting points for your own app.
- The examples running online: surveyjs-aspnet-mvc.demos.surveyjs.io
- SurveyJS demos: app.demos.surveyjs.io
- The same examples for other platforms: PHP (Laravel), Node.js (Express), Python (FastAPI), Next.js, Java (Spring Boot)
You need the .NET 10 SDK. Docker runs the SurveyJS service for the four Run Server-Side Workflows examples, and Node.js 22 or later is only for the browser tests, the CSS build and the contract test (see Prerequisites).
git clone https://github.com/surveyjs/surveyjs-aspnet-core.git
cd surveyjs-aspnet-core
dotnet run # http://127.0.0.1:8000
docker compose up -d surveyjs # the SurveyJS service, for Run Server-Side WorkflowsThe first start creates the SQLite database in storage/ from the committed migrations and seeds it. dotnet run uses the http profile in Properties/launchSettings.json (the Development environment, no HTTPS certificate needed).
- Fill Forms Together and Edit Forms Together use WebSocket relays that run inside the app, on its port (
/ws/rooms/<id>and/ws/forms/<id>). There is nothing else to start. - Run Server-Side Workflows (validate, lint, PDF, extract) call the SurveyJS service, SurveyJS Server.
docker compose up -d surveyjsstarts it onhttp://localhost:3010. To switch Validate Responses and Lint JSON Schemas on, setVALIDATE_RESPONSES=trueandLINT_DEFINITIONS=true(inappsettings.Development.json, copied fromappsettings.Development.json.example, or as environment variables), then restart the app. Extract Responses from Documents also needs an AI provider for the service (SURVEYJS_AI_PROVIDERand its key). - The tests:
dotnet test tests/SurveyJs.Tests: the xUnit tests, the app in memory with a temporary database per test class, no browser and no network (the SurveyJS service is a stub).dotnet run --project tools/Contract: the shared contract test against the built app and a fresh database. Add-- --smokefor the smoke test, or-- --steps save-response,dashboardfor some examples. With the service running, setSERVICE=on($env:SERVICE="on"in PowerShell).npm ci,npx playwright install chromiumonce, thendotnet buildandnpm run test:browser: the shared Playwright specs.dotnet run --project tools/Check: the manifest, the regions,shared/and the pins.
Before it starts, the app checks that nothing answers on its port. Once it is up, it prints the folder it serves and its <branch>@<commit>:
Serving C:\src\surveyjs-aspnet-core (master@4a96b83) on http://127.0.0.1:8000
- The .NET 10 SDK (10.0.400 or a later feature band;
global.jsonpins it).- Without it,
dotnet runstops with .NET's own message: "A compatible .NET SDK was not found. Requested SDK version: 10.0.400", followed by the SDKs you have. Install the .NET 10 SDK from dot.net. dotnet --list-sdksshows what you have.
- Without it,
- Docker for the SurveyJS service (
docker compose up -d surveyjs). Without it, the four Run Server-Side Workflows examples answer503"SurveyJS service is not running at http://localhost:3010", and everything else works. - Node.js 22 or later, only for the browser tests, the CSS build and the contract and smoke tests (they are
shared/*.mjs).npm cion an older Node stops with npm's ownEBADENGINEerror (enginesinpackage.json,engine-strictin.npmrc). Running the app never needs Node: the built stylesheet is committed.
On Windows:
-
Install the SDK with
winget install Microsoft.DotNet.SDK.10, or from dot.net. -
After installing the SDK or Node, restart your editor, not only its terminal: VS Code's terminals inherit VS Code's environment, so a terminal in an editor started before the install doesn't see the new
PATH. To refresh the current PowerShell terminal instead:$env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User') dotnet --list-sdks
-
The app listens on
127.0.0.1by default (APP_HOST), so Windows Defender Firewall doesn't ask whether it may accept network connections. -
Set a variable for one run like this, or put it in
appsettings.Development.json:$env:APP_PORT=8001; dotnet run
APP_PORT=8001 dotnet run
APP_HOSTandAPP_PORTdecide where the app listens, also whenASPNETCORE_URLSis set.
On Windows a second server can start on a port another one holds, and the first one keeps answering. So the app connects to its port before it starts, and stops with exit code 1 when anything answers:
Port 8000 is already in use. Another copy of this app (another checkout or branch?) may be running. Stop it, or set APP_PORT.
Ctrl+C in the terminal, then docker compose down for the service. To find a server left running in another terminal or checkout:
Get-NetTCPConnection -LocalPort 8000 -State Listen | Select-Object OwningProcess
Stop-Process -Id <OwningProcess>lsof -i :8000
kill <PID>- Check the branch out in its own folder, with
git worktree add ../surveyjs-aspnet-core-pr <branch>(for a pull request, rungit fetch origin pull/<number>/head:pr-<number>first) or a second clone. Each checkout has its ownappsettings.Development.json,storage/andbin/. - Run one checkout on the default port at a time: stop the other one first, or start the second with
APP_PORT=8001. - The SurveyJS service is shared:
docker-compose.ymlnames its projectsurveyjs-aspnet, so every checkout manages the same container. - The page says which checkout answered: "Running
<branch>@<commit>" under the catalog's footer buttons and at the end of every example's Description panel.
docker compose up --build # http://127.0.0.1:8000, with the SurveyJS service next to itThe image (Dockerfile).
- Build and run. It publishes the app with
mcr.microsoft.com/dotnet/sdk:10.0and runs it onmcr.microsoft.com/dotnet/aspnet:10.0, as the image's non-rootappuser, withdotnet surveyjs-aspnet-core.dllas PID 1. - What it holds. The published output includes
shared/,surveyjs-integration.json, the example sources the Code tab shows, and the SurveyJS packages' files underwwwroot/_content/. - Settings. Its environment sets
ASPNETCORE_ENVIRONMENT=Production,APP_HOST=0.0.0.0,DATA_DIR=/app/storageandASPNETCORE_FORWARDEDHEADERS_ENABLED=true. Real environment variables win overappsettings.json. - Data. On its first start it migrates and seeds the database, from the compiled migrations: no SDK, no
dotnet ef. Its one volume,/app/storage, holds the database, the uploads, the visitor sandboxes and the relay snapshots. - Health.
GET /upanswers200 Healthywithout touching the database.
One process, many visitors. Kestrel serves requests concurrently, so an extraction that waits up to 120 seconds for the service doesn't block anyone else. Run one process per data volume: the relay rooms, the countries cache and the demo's AI counter live in its memory. Scaling out to several processes needs a shared room store (for example SignalR with a Redis backplane, or Redis pub/sub) and a server database; both are out of scope here.
On Windows, Docker Compose 5 can't build a service from a git URL (failed to evaluate path "https://github.com/…"), and the surveyjs service is one. It hands the URL to the builder as a file path. Let Compose print the build and give it to the builder yourself, then start without building:
docker compose build --print | docker buildx bake -f -
docker compose up -d --no-buildASPNETCORE_FORWARDEDHEADERS_ENABLED=true makes ASP.NET Core trust X-Forwarded-For and X-Forwarded-Proto from any proxy. Behind a TLS proxy, the pages' absolute URLs and the relays' wss:// URLs then use the scheme the visitor sees, and the demo's Secure cookies work.
In your own production, narrow it to your proxy: configure ForwardedHeadersOptions.KnownProxies (or KnownNetworks) with UseForwardedHeaders() instead of the variable, and don't publish the app's port.
The relays are on the app's own host and port, so the proxy needs no extra route. It only has to pass WebSocket upgrades through on /ws/. For Traefik, next to your entry point and TLS labels:
services:
app:
labels:
- traefik.http.routers.surveyjs.rule=Host(`example.com`)
- traefik.http.services.surveyjs.loadbalancer.server.port=8000- Traefik passes WebSocket upgrades on by default.
- nginx needs
proxy_set_header Upgrade $http_upgrade;andproxy_set_header Connection "upgrade";on/ws/. - Azure App Service: switch Web sockets on in the app's configuration.
RELAY_URL and EDIT_RELAY_URL are only needed when /ws/ is served from another origin. The SurveyJS service stays internal (expose: ["3000"]): only the app calls it.
Configuration/SurveyJsOptions.cs binds every setting once. Code reads IOptions<SurveyJsOptions>, never the environment. The keys are the cross-platform names, so environment variables, appsettings.json, appsettings.Development.json and the contract runner use the same words as the other platforms. Environment variables win over both files. appsettings.Development.json.example lists them all: copy it to appsettings.Development.json (git-ignored) to change a setting for dotnet run. Switches accept 1, true, on or yes; a blank value means unset.
| Setting | Default | What it does |
|---|---|---|
APP_PORT, APP_HOST |
8000, 127.0.0.1 |
Where the app listens. |
DATA_DIR |
storage |
The SQLite database, uploads, sandboxes and relay snapshots. |
SURVEYJS_SERVICE_URL |
http://localhost:3010 |
The SurveyJS service (docker compose up -d surveyjs). In Compose, the app uses http://surveyjs:3000. |
VALIDATE_RESPONSES |
false |
Validate Responses: MapValidateResponse() replaces MapSaveResponse(). |
LINT_DEFINITIONS |
false |
Lint JSON Schemas: MapLintDefinition() replaces the PUT of MapCreatorLoadSave(). |
SURVEYJS_AI_PROVIDER, SURVEYJS_AI_MODEL, SURVEYJS_OLLAMA_BASE_URL, OPENAI_API_KEY, ANTHROPIC_API_KEY |
empty | Extract Responses from Documents: Compose passes them to the service as AI_PROVIDER, AI_MODEL and OLLAMA_BASE_URL (openai, anthropic or ollama). Docker Compose reads them from your shell or a .env file, not from appsettings.*.json. The app reads them only for the page's banner. |
AI_BASE_URL, AI_API_KEY, AI_MODEL |
OpenAI, empty, gpt-4o-mini |
Translate with AI: any OpenAI-compatible /chat/completions endpoint. Without a key, /api/translate answers 501. |
SURVEYJS_LICENSE_KEY |
empty | Calls setLicenseKey() on every page. Without it, the commercial components show a licence banner. The service at its pinned revision ignores it, so server PDFs carry the SurveyJS alert banner. |
RELAY_URL, EDIT_RELAY_URL |
empty | The relays' origin when a proxy serves /ws/ elsewhere, for example wss://example.com. Empty: the page's own origin. |
DEMO_MODE |
false |
The hosted demo's visitor sandboxes (below). |
SURVEYJS_BUILD |
from git | The <branch>@<commit> the pages show as "Running …". Read from git in Development; deploys set it themselves. |
SurveyJs:Docs, SurveyJs:GitHub |
the ASP.NET Core docs page, this repository | Where the pages link (SurveyJs__Docs as an environment variable). |
Each example is two or three files you can read on their own. The full explanation is in the docs.
Endpoints/<PascalSlug>.cs: the example's minimal API endpoints, the server code the docs show. Each file is aMapX()extension method thatProgram.cscalls in the docs' order.MapValidateResponse()replacesMapSaveResponse(), andMapLintDefinition()replacesMapCreatorLoadSave(), when their switches are on.FillTogether.csandEditTogether.csare the two relays, WebSocket endpoints; their rooms are inRelay/.- The
/claimpage of Load JSON Schemas, Variables, and Answers is a Razor page model:Pages/Examples/LoadDefinitionVariablesData.cshtml.cs.
shared/client/<slug>.js: the example's client code, a plain ES module, the same file on every platform.Pages/Examples/<PascalSlug>.cshtml: the example's page: its description, the "Try this" list and the component.Integration/: small helpers some endpoints call, so the code the docs show stays about SurveyJS. They aren't demo code:StoredJson.cs: the raw-body parsing, the serializer options,InsertResponseAsync(),UpsertAsync()and the UTC timestamp (see below).SurveyJsService.cs: the typedHttpClientfor the SurveyJS service, with a timeout per call, the 503, 504 and 502 when the service doesn't answer, and the logging.AiTranslationClient.cs: the call to your OpenAI-compatible provider.FileType.cs: file types by their first bytes.ApiErrors.cs: the{ error }shape for every error under/api.
- The rest:
Data/: theDbContext, the entities, the migrations and the seeder.Authorization/: theedit-formsandread-filepolicies.Configuration/: the settings, the port check and the build line.
To copy an example, copy its endpoint file and the helpers it uses. The code the docs show is cut from these files between #region sjs:<slug>.server and #endregion (and // #region sjs:<slug>.client in the client modules). surveyjs-integration.json lists every example's files and regions, and dotnet run --project tools/Check verifies them.
shared/ holds what every platform repository uses byte for byte: the client modules, the form definitions, samples and seed data, the page UI (shared/ui/), and the contract, smoke and browser tests. It is a copy of surveyjs-php-laravel's shared/ at the commit in shared/UPSTREAM, and the check command compares it with shared/SHA256SUMS. Don't edit it here: send a fix to that repository, then copy shared/ again. .gitattributes keeps it in LF on Windows checkouts too; otherwise every hash would fail.
The text in an example's Description panel is the description section of Pages/Examples/<PascalSlug>.cshtml. It can hold several paragraphs, links and other markup:
@section description {
<p>Your custom description.</p>
<p>More details with <strong>formatting</strong>.</p>
}- The other parts: the "Try this" list is the
tryThissection (tryis a C# keyword), the layout isPages/Shared/_ExampleLayout.cshtml, and the catalog (Pages/Index.cshtml) takes each card's "Use when" text fromneedinsurveyjs-integration.json. - Seeing an edit: restart
dotnet run, or usedotnet watch. If you used a Tailwind class no other page uses, rebuild the stylesheet too (see Front end).
A response, a definition, saved progress and variable presets are each one JSON document, stored as text and returned as stored.
- The raw body, not model binding. A .NET developer reaches for a bound model there, but a class (or a
Dictionary<string, object>) drops the keys it doesn't declare and re-formats numbers. The storing endpoints read the raw body withStoredJson.ReadBodyAsync(request)and parse it withJsonNode.Parse. That keeps every key,{},[{}],null,"", whitespace inside strings and the number text (1.0stays1.0). A comment in each endpoint says why. Translate with AI stores nothing, so it binds a record. - Written back compactly.
StoredJson.OptionsusesJavaScriptEncoder.UnsafeRelaxedJsonEscaping, so"naïve — 東京"and"/api/files/1"are stored as they are, not as\uescapes. These strings go to the database and to JSON answers, never into HTML. - Strings, not mapped classes. The document columns are
stringproperties on the entities. There is noToJson(), owned type or complex type, which would map the document to classes. - Dates are strings.
created_atis ISO 8601 UTC to the second (2026-11-17T13:36:06Z, written withCultureInfo.InvariantCulture), so the dashboard's date filters are string comparisons. - Errors are
{ error }. Under/api, every error is{ "error": … }, also the framework's own: a body that isn't JSON is a400, and so are a bad query value (limit=abc), an unknown route (404), a wrong method (405), a JSON post to an upload endpoint (415) and an unexpected exception (500 { "error": "Internal server error" }). The error writer isIntegration/ApiErrors.cs; nothing answers with ProblemDetails.
The examples store their tables in SQLite (storage/database.sqlite) through Entity Framework Core.
-
The data layer. There is one entity class per table (
Data/Entities.cs), with[Table]and[Column]attributes for the names the docs use.Data/SurveyDb.csis theDbContext, and the committed migrations inData/Migrations/create the tables on start (MigrateAsync()).Data/Seeder.cs, EF Core's seeding hook, seeds them fromshared/seed/. It adds missing forms on every start, and fills the other tables only when they are empty. -
Queries. The endpoints use LINQ over the
DbSets. A field inside a stored document is read with SQLite'sjson_extract, mapped asSurveyDb.JsonValue(r.Data, "$.customer_email"). Writes of one document under a key go throughStoredJson.UpsertAsync(), oneINSERT … ON CONFLICTstatement, because EF Core has no upsert. The only SQL in the code isExecuteSql/FromSqlwith interpolated parameters, never theirRawforms. -
After changing an entity, add a migration and commit it. A test fails when the model and the migrations differ.
dotnet tool restore dotnet ef migrations add <Name> --output-dir Data/Migrations
-
Look inside with the
sqlite3command-line shell:sqlite3 storage/database.sqlite "SELECT id, form_id, data FROM responses ORDER BY id DESC LIMIT 5"The
-waland-shmfiles next to it belong to the database (EF Core opens SQLite in WAL mode). Stop the app and deletestorage/to start over: the next start creates and seeds everything again. -
Not EF Core? Plain
Microsoft.Data.Sqliteor Dapper with aTEXTcolumn works just as well; keep the documents as text.
Locally, everyone shares one database, storage/database.sqlite. Delete storage/ to start over.
On a hosted demo (DEMO_MODE=true), each visitor gets a private copy of the seeded database and their own uploads folder:
- The sandbox. A
demo_sidcookie picks it. It is created on first use (SqliteConnection.BackupDatabase, which also copies what is still in the-walfile), and kept until it has been unused for 24 hours. The cleanup is aBackgroundServicein the app,Demo/DemoSandbox.cs. - Sharing. The "Open a second window" link in Fill Forms Together and Edit Forms Together carries that id (
?join=), so whoever opens it works in the same copy and the same relay rooms. - Limits. The demo caps uploads at 5 MB per file and the AI examples at 20 calls per visitor per day, with ASP.NET Core's rate limiter.
- Not in the example code. The
DemoSandboxmiddleware points a scopedRequestStorageservice at the visitor's files.SurveyDband the upload endpoints read it, so the endpoints don't change.
- The pages. They are Razor Pages (
Pages/), HTML-encoded by default. Each page diffs against its Blade source in the reference repository only in template syntax, with the Tailwind class strings unchanged. Inline JSON (the page config,window.FORM_DEFINITION,window.FORM_VARIABLES) is written with@Json.Serialize(…), which escapes<,>and&, so a</script>in a definition can't end the script. No value from the database is ever@Html.Raw. - The stylesheet. It is Tailwind CSS v4 without Preflight.
Styles/site.cssimportstailwindcss/theme.css(static),tailwindcss/utilities.cssandshared/ui/theme.css.npm run cssbuilds it intowwwroot/css/site.csswith@tailwindcss/cli. The output is committed, sodotnet runnever needs Node; CI rebuilds it and fails on a difference.- Rebuild it after editing a page. The Tailwind standalone binary builds the same file without Node:
tailwindcss -i Styles/site.css -o wwwroot/css/site.css --minify.
- SurveyJS comes from the NuGet packages (
SurveyJS,SurveyJS.Creator,SurveyJS.Analytics).- ASP.NET Core serves their ES module builds as static web assets under
/_content/SurveyJS.*/, with npm's paths:/_content/SurveyJS.Core/fesm/survey-core.mjsis npm'ssurvey-core/fesm/survey-core.mjs. - The shared modules in
shared/client/andshared/ui/load unchanged with<script type="module">and an import map (Demo/ImportMap.cs), which points each SurveyJS specifier at those files. At start, the app checks that each one exists. The ES module builds are in the packages from SurveyJS 3.2.6; an older version stops the app with the missing package file.
- ASP.NET Core serves their ES module builds as static web assets under
- The third-party modules come from unpkg.
chart.jsand@kurkle/color(whichsurvey-analyticsimports),lodash-esand highlight.js are in no SurveyJS package, so the import map points them at unpkg at pinned versions. Self-host them by copying their files intowwwroot/and changing the URLs inDemo/ImportMap.cs. - Don't mix the two builds. Don't put the packages' script-tag builds (
survey.core.min.jsand friends) and the ES modules on one page: they would load SurveyJS twice. - Highlighting. The Code tab highlights the C# regions with highlight.js's
csharplanguage. The import map has an entry for every languageshared/ui/code-highlight.jsimports. - Theming. The forms use the SurveyJS Tailwind adapter (
survey-core/themes/adapters/tailwind4.min.css). No page callsapplyTheme(): its inline styles would override the adapter.
The endpoints only use the request, the database and the response, so they port in a few lines. Save Responses as an MVC controller action, reading the raw body for the same reason:
[ApiController]
public class ResponsesController(SurveyDb db) : ControllerBase
{
[HttpPost("/api/responses")]
public async Task<IActionResult> Save()
{
// Read the raw request body: binding to a class would drop unknown keys and re-format numbers such as 1.0
if (await StoredJson.ReadBodyAsync(Request) is not JsonObject body
|| body["formId"] is not JsonValue formId || body["data"] is not JsonNode data)
{
return BadRequest(new { error = "Expected { formId, data }" });
}
var id = await StoredJson.InsertResponseAsync(db, formId.ToString(), data);
return StatusCode(201, new { id });
}
}Only the request and response wrappers change.
These examples must not be used as a real service as they are. They don't cover authentication, authorization, user management, access levels and other security aspects of a real survey service. The places where real checks go are marked:
Authorization/EditFormsRequirement.cs: theedit-formspolicy, which decides who may save definitions and presets and join the edit-together relay.Authorization/ReadFileHandler.cs: theread-filepolicy, which decides who may read an uploaded file.Demo/DemoUsers.cs: the demo authentication handler. It reads ademo_usercookie; your app authenticates there with cookie or JWT authentication (AddCookie(),AddJwtBearer()).- Antiforgery. The two upload endpoints call
.DisableAntiforgery()because the pages call them withfetch()from the same origin. With cookie authentication, validate an antiforgery token or send anAuthorizationheader instead.
When you copy an example into your app, leave out the demo-only code:
- the
Demo/folder, and its lines inProgram.cs; Relay/RoomKey.cs's sandbox keys;Pages/,shared/ui/(the page frame, its tabs and highlighting, the fonts and site images) andshared/client/host.js. ItsmountSurvey()is one line:renderSurvey(survey, element)fromsurvey-js-ui.
The Endatix Platform is an open-source solution that provides a fully integrated server-side API for managing SurveyJS forms and their results within .NET environments. Endatix provides a complete backend application structure, from API requests to database integration and admin management, allowing users to quickly implement a fully operational server environment with minimal coding. Endatix is an ideal choice for developers looking for an efficient way to implement SurveyJS without extensive server-side development.
Endatix Platform repo: https://github.com/endatix/endatix