C# Inline Probe

Illustrates using the C# inline capability to craft a probe in code when PowerShell alone is insufficient or you want direct .NET API access.

Full source

File: pwsh/tutorial/examples/16.5-Health-CSharp-Probe.ps1

<#
 C# Inline Probe Example
 Demonstrates an inline C# probe computing a random success/failure.
#>
param(
    [int]$Port = 5000,
    [IPAddress]$IPAddress = [IPAddress]::Loopback
)
## 1. Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault

## 2. Server
New-KrServer -Name 'Health CSharp Probe'

## 3. Listener (port 5000)
Add-KrEndpoint -Port $Port -IPAddress $IPAddress

#
## 5. Enable configuration
Enable-KrConfiguration

$csharp = @'
using System;
using System.Collections.Generic;
using Kestrun.Health;
public static class ProbeImpl {
    public static ProbeResult Run() {
        var rnd = new Random();
        int value = rnd.Next(0,100);
        var status = value < 70 ? ProbeStatus.Healthy : (value < 90 ? ProbeStatus.Degraded : ProbeStatus.Unhealthy);
        return new ProbeResult(status, $"Random value={value}", new Dictionary<string,object?> { {"value", value } });
    }
}
ProbeImpl.Run();
'@

## 6. C# inline code compiled/executed at runtime
Add-KrHealthProbe -Name 'RandomCSharp' -Tags 'self', 'random' -Code $csharp -Language CSharp

## 7. Health endpoint
Add-KrHealthEndpoint -Pattern '/healthz' -DefaultTags 'self', 'random' -ProbeTimeout '00:00:05'

## 8. Start server
Start-KrServer

Step-by-step

  1. Register a script-based probe that uses inline C# code within the handler.
  2. Create and return a ProbeResult with status and data fields.
  3. Optionally randomize or branch to demonstrate different states.
  4. Start the server and query /healthz.

Try It

Invoke-RestMethod http://127.0.0.1:5004/healthz | ConvertTo-Json -Depth 4

Run multiple times to observe varying statuses.

Troubleshooting

Symptom Cause Fix
Compilation error Inline C# syntax issue Validate C# snippet separately before embedding
Missing data fields Not added to dictionary Ensure dictionary keys are set before returning result

References


Previous / Next

Previous: Process Probe Next: Disk Probe