Low-Level Response Stream
Direct manipulation of $Context.Response.Body stream for scenarios requiring manual control over response writing. Use only when higher-level helpers do not fit.
Full source
File: pwsh/tutorial/examples/9.10-Low-Level-Response.ps1
<#
Sample: Low-Level Response
Purpose: Demonstrate raw stream response in a Kestrun server.
File: 9.10-Low-Level-Response.ps1
Notes: Shows direct stream writing for custom scenarios.
#>
param(
[int]$Port = 5000,
[IPAddress]$IPAddress = [IPAddress]::Loopback
)
# 1. Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault
# 2. Server
New-KrServer -Name 'Responses 9.10'
# 3. Listener
Add-KrEndpoint -IPAddress $IPAddress -Port $Port
# Finalize configuration
Enable-KrConfiguration
# Raw stream route
Add-KrMapRoute -Pattern '/raw' -Verbs GET -ScriptBlock {
$Context.Response.ContentType = 'text/plain'
$Context.Response.StatusCode = 200
$bytes = [System.Text.Encoding]::UTF8.GetBytes('raw-stream-data')
$Context.Response.Body.Write($bytes, 0, $bytes.Length)
}
# Start the server
Start-KrServer
Step-by-step
- Logging: Register console logger as default.
- Server: Create server named ‘Responses 9.10’.
- Listener: Listen on 127.0.0.1:5000.
/raw: Sets ContentType and StatusCode directly on Response object.- Converts string to UTF-8 bytes and writes directly to Response.Body stream.
- Enable configuration and start server.
Try it
curl -i http://127.0.0.1:5000/raw
PowerShell equivalents:
# Get raw response content
Invoke-WebRequest -Uri http://127.0.0.1:5000/raw | Select-Object -ExpandProperty RawContent
# Get just the response body
Invoke-WebRequest -Uri http://127.0.0.1:5000/raw | Select-Object -ExpandProperty Content
Example route
# Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault
# Server
New-KrServer -Name 'Responses 9.10'
# Listener
Add-KrEndpoint -IPAddress '127.0.0.1' -Port 5000
# Enable configuration
Enable-KrConfiguration
# Raw stream route
Add-KrMapRoute -Pattern '/raw' -Verbs GET -ScriptBlock {
$Context.Response.ContentType = 'text/plain'
$Context.Response.StatusCode = 200
$bytes = [System.Text.Encoding]::UTF8.GetBytes('raw-stream-data')
$Context.Response.Body.Write($bytes, 0, $bytes.Length)
}
# Start the server
Start-KrServer
When to use
| Situation | Rationale |
|---|---|
| Custom serialization pipeline | Encoder already writes to a stream |
| Chunked / progressive output | Manually control flush timing |
| Experimental formats | No dedicated helper yet |
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Empty response | No bytes written | Ensure bytes are written to Body |
| Wrong content type | Not set on Response | Set $Context.Response.ContentType |
| Garbled text | Wrong encoding | Use UTF-8 when converting to bytes |
References
Previous / Next
- Previous: Content Negotiation
- Next: Responses Overview