Redirects

Send 3xx status and a Location header using Write-KrRedirectResponse.

Full source

File: pwsh/tutorial/examples/9.6-Redirects.ps1


<#
    Sample: Redirects
    Purpose: Demonstrate HTTP redirects in a Kestrun server.
    File:    9.6-Redirects.ps1
    Notes:   Shows 3xx Location header response.
#>
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.6'

# 3. Listener
Add-KrEndpoint -IPAddress $IPAddress -Port $Port


# Finalize configuration
Enable-KrConfiguration

# Redirect route
Add-KrMapRoute -Pattern '/old' -Verbs GET -ScriptBlock {
    Write-KrRedirectResponse -Url 'https://example.com/new' -Message 'Resource moved to /new'
}

# Start the server
Start-KrServer

Step-by-step

  1. Logging: Register console logger as default.
  2. Server: Create server named ‘Responses 9.6’.
  3. Listener: Listen on 127.0.0.1:5000.
  4. Runtime: Add PowerShell runtime.
  5. /old: issues redirect with message body.
  6. Enable configuration and start server.

Try it

curl -i http://127.0.0.1:5000/old

PowerShell equivalents:

# See redirect headers (302 status and Location header)
Invoke-WebRequest -Uri http://127.0.0.1:5000/old -MaximumRedirection 0 -ErrorAction SilentlyContinue | Select-Object StatusCode, Headers

# Follow the redirect automatically (default behavior)
try {
    Invoke-WebRequest -Uri http://127.0.0.1:5000/old | Select-Object StatusCode, BaseResponse
} catch {
    Write-Host "Redirect followed to: $($_.Exception.Response.Headers.Location)"
}

# View raw response including headers
Invoke-WebRequest -Uri http://127.0.0.1:5000/old -MaximumRedirection 0 -ErrorAction SilentlyContinue | Select-Object -ExpandProperty RawContent

Redirect Types

# Basic redirect (302 Found)
Add-KrMapRoute -Pattern '/old' -Verbs GET -ScriptBlock {
    Write-KrRedirectResponse -Url 'https://example.com/new' -Message 'Resource moved to /new'
}

# Redirect with custom message
Add-KrMapRoute -Pattern '/moved' -Verbs GET -ScriptBlock {
    Write-KrRedirectResponse -Url '/new-location' -Message 'This resource has permanently moved'
}

# Local redirect (within same domain)
Add-KrMapRoute -Pattern '/legacy' -Verbs GET -ScriptBlock {
    Write-KrRedirectResponse -Url '/api/v2/data' -Message 'Please use the new API endpoint'
}

Default status code is typically 302. Use low-level middleware (future enhancement) if you require 301/307/308 variants.

Troubleshooting

Symptom Cause Fix
Redirect not followed Client auto-follow disabled Remove -MaximumRedirection 0
Wrong Location header Relative URL unexpected Use absolute URL when needed
Status not 302 Client shows cached 301 Clear cache or use a different URL

References


Previous / Next

Previous: Special Formats (BSON / CBOR) Next: Errors