Responses Overview
Return data to clients using purpose-built helpers for common content types: text, JSON, YAML, XML, CSV, HTML, files, streams, binary, BSON, CBOR. They also simplify redirects, errors and HTTP caching primitives.
These cmdlets wrap the underlying ASP.NET Core primitives. They keep route script blocks concise while still letting you customize status codes, headers and serialization.
Chapters
| # | Topic | Highlights |
|---|---|---|
| 1 | Text & JSON | Plain text, JSON serialization depth & compression |
| 2 | Structured (XML / YAML / CSV) | Alternative serializations, custom content types |
| 3 | Binary & Stream | Raw bytes, streaming large content |
| 4 | HTML Templates & Files | File + template rendering, file download headers |
| 5 | Special Formats (BSON / CBOR) | Compact binary object encodings |
| 6 | Redirects | 3xx responses + optional message body |
| 7 | Errors | Consistent error payloads, exceptions & stack traces |
| 8 | Caching & Revalidation | Cache-Control, ETag, Last-Modified, 304 handling |
| 9 | Low-Level Response Stream | Direct stream writing when you need full control |
| 10 | Health Checks | Aggregate endpoint, script/HTTP/process probes |
Quick Start
Minimal server returning JSON & text:
New-KrServer -Name 'Responses Demo'
Add-KrEndpoint -Url 'http://127.0.0.1:5055'
Add-KrMapRoute -Path '/hello' -Method GET -ScriptBlock {
Write-KrTextResponse 'Hello world from text'
}
Add-KrMapRoute -Path '/data' -Method GET -ScriptBlock {
[PSCustomObject]@{ message = 'Hi'; time = (Get-Date) } | Write-KrJsonResponse -Compress
}
Enable-KrConfiguration
Start-KrServer | Out-Null
Then:
curl http://127.0.0.1:5055/hello
curl http://127.0.0.1:5055/data
Cmdlets Covered
Write-KrTextResponseWrite-KrJsonResponseWrite-KrXmlResponseWrite-KrYamlResponseWrite-KrCsvResponseWrite-KrHtmlResponseWrite-KrFileResponseWrite-KrBinaryResponseWrite-KrStreamResponseWrite-KrBsonResponseWrite-KrCborResponseWrite-KrRedirectResponseWrite-KrErrorResponseAdd-KrCacheResponseTest-KrCacheRevalidationWrite-KrResponse(low-level)
Choosing a Helper
| Scenario | Use |
|---|---|
| Simple text or diagnostics | Write-KrTextResponse |
| API returning objects | Write-KrJsonResponse |
| Legacy / interop requirements | Write-KrXmlResponse |
| Configuration style payloads | Write-KrYamlResponse |
| Tabular export | Write-KrCsvResponse |
| Page or fragment templating | Write-KrHtmlResponse |
| Download / inline file | Write-KrFileResponse |
| Large file / custom generation | Write-KrStreamResponse |
| Binary blob already buffered | Write-KrBinaryResponse |
| High density object format | Write-KrBsonResponse or Write-KrCborResponse |
| Set Location & 3xx status | Write-KrRedirectResponse |
| Consistent problem payload | Write-KrErrorResponse |
| Cache headers (max-age etc.) | Add-KrCacheResponse |
| ETag / 304 negotiation | Test-KrCacheRevalidation |
| Full control (edge cases) | Write-KrResponse |
Next
Previous: Authentication Next: Text & JSON