Tutorials

Step-by-step guides to build and ship with Kestrun. This index lists runnable sample scripts and documentation chapters in recommended learning order.

Prerequisites

  • PowerShell 7.4, 7.5, or 7.6 (RC)
  • .NET (run-only scenarios do NOT require the full SDK)
PowerShell Version Install (Run Samples) Notes
7.4 / 7.5 .NET 8 ASP.NET Core Runtime Bundles base runtime + ASP.NET Core
7.6 .NET 10 ASP.NET Core Runtime Bundles base runtime + ASP.NET Core

If you already have the .NET SDK for those versions installed you don’t need to install the runtime separately.

  • Kestrun module: installed or available from this repository at src/PowerShell/Kestrun/Kestrun.psm1
  • Supported OS: same as .NET 8/10 (Windows, Linux, macOS), including ARM/ARM64

Verify (optional):

dotnet --list-runtimes | Where-Object { $_ -match 'Microsoft.(AspNetCore|NETCore).App' }

You should see Microsoft.AspNetCore.App 8.0.x (and 10.0.x if using PowerShell 7.6 ).

Quick start: run the samples

From the repository root:

# 1) Hello World
pwsh .\examples\PowerShell\Tutorial\1-Hello-World.ps1

Then browse the routes (default listener: http://127.0.0.1:5000): Read the note on each sample for the routes detail.

Stop the server with Ctrl+C in the terminal.

Samples & Chapters Overview

Order Topic Chapter Sample Script Focus
1 Introduction Hello World Script This sample spins up a small Kestrun server and returns plain text from a single route.
2 Routes Multiple Content Types Script Return text, JSON, XML, and YAML from different routes.
3 Routes Multi-language Routes (PS/C#/VB) Script Map routes in PowerShell and implement others inline in C# or VB.NET.
4 Routes Route Parameters & Request Data Script Read data from different parts of the incoming HTTP request: path (route) parameters, query string, body (form / JSON), headers, and cookies.
5 Routes Route Options (MapRouteOptions) Script Use MapRouteOptions / New-KrMapRouteOption to configure routes with richer metadata, different languages, and advanced behaviors.
6 Routes Route Groups Script Group related routes under a shared URL prefix to remove repetition, keep concerns
7 Static Routes Serving Static Files Script Expose folders of files (HTML, CSS, JS, images, etc.) over HTTP using the static files service.
8 Static Routes File Server & Directory Browsing Script Serve a directory tree with optional HTML listings and custom MIME mappings.
9 Static Routes Static Route Overrides Script Inject dynamic responses at specific file paths under a static directory.
10 Static Routes Adding a Favicon Script Add a site icon (favicon.ico / PNG) so browsers display your brand in tabs and bookmarks.
11 Static Routes File Server Caching Headers Script Add HTTP cache directives (Cache-Control) directly to static file responses served by the file server middleware.
12 Static Routes Response Caching & Conditional Requests Script Layer fine‑grained dynamic caching and validator logic on top of (or independent from) file server level
13 Shared Variable Using Shared Variables Script Share in-memory state (counters, caches, configuration) by defining variables before Enable-KrConfiguration
14 Shared Variable Managing Shared State Script Use the Kestrun shared state cmdlets (Set-KrSharedState, Get-KrSharedState, Remove-KrSharedState) to create
15 Logging Simple Logging Script Introduce structured logging early: create a named logger with console + rolling file sinks, register it as
16 Logging Multiple Loggers & Levels Script Run more than one named logger at once and control their verbosity separately.
17 Logging Enrichment & Correlation IDs Script Attach useful properties (enrichment) to your log events and add a per-request
18 Logging Sinks (Console/File/JSON) Script Wire different outputs for your logs.
19 Logging Sinks (HTTP/EventLog/Syslog) Script Push logs to external systems.
20 Logging Hot Reload (Update Logger) Script Change logging behavior without restarting the server.
21 Logging Apache Common Access Log Script Add structured request logging in the classic Apache Common Log Format (CLF) (also called Common Access Log).
22 Certificates Create a Self‑Signed Certificate Script Generate a development certificate for localhost and bind it to an HTTPS listener.
23 Certificates Generate a CSR (Certificate Signing Request) Script Run a small API that generates a CSR from request parameters.
24 Certificates Import, Export, Validate & EKU Script Expose API endpoints to import a certificate and export it in different formats, with simple validation and EKU reporting.
25 Endpoints Basic Server Script Minimal server: one HTTP listener (loopback:5000) + a single PowerShell route returning text.
26 Endpoints Multiple Listeners Script Serve the same routes on more than one port / interface.
27 Endpoints HTTPS & Certificates Script Add TLS with a development self‑signed certificate or an existing PFX.
28 Endpoints Named Pipes (Windows) Script Bind Kestrun to a Windows named pipe for local IPC instead of a TCP port.
29 Endpoints Unix Sockets Script Bind to a Unix domain socket instead of TCP for local reverse proxy performance.
30 Endpoints Mixed HTTP Protocols Script Expose the same application over multiple listeners each constrained to a specific HTTP protocol version
31 Endpoints URI Endpoint Script Demonstrates using a pre-built System.Uri with Add-KrEndpoint -Uri instead of separately specifying
32 Authentication Basic (PowerShell) Script Define a Basic auth scheme with a PowerShell script block validating username/password.
33 Authentication Basic (C# / VB.NET) Script Implement credential validation in C# and VB.NET while retaining PowerShell host scripts.
34 Authentication API Key Script Validate requests using an API key header (fixed value, script, or inline C#/VB code).
35 Authentication JWT Tokens Script Issue and validate bearer tokens for stateless auth.
36 Authentication Cookies Script Maintain user sessions with a login form + cookie session authentication.
37 Authentication Windows Authentication Script Leverage the host (Windows / Active Directory) credentials for transparent authentication.
38 Authentication Claims & Policies Script Define claim-based authorization rules and enforce them per route.
39 Authentication Client Certificate Script Authenticate requests using client TLS certificates (mTLS).
40 Authentication OpenID Connect (Okta) Script Add Okta login using the authorization code flow with PKCE and persist the session via cookies.
41 Authentication Multiple Schemes Script Combine several authentication mechanisms (Basic, API Key, JWT Bearer) in a single server and allow
42 Authentication GitHub Authentication Script Enable GitHub OAuth login with a ready-made wrapper that configures PKCE, token persistence, and session cookie forwarding.
43 Authentication Full Demo Script Integrated example combining Basic, API Key, JWT, Cookies, claims & policies.
44 Authentication OpenID Connect (Duende Demo) Script Authenticate users via OpenID Connect using the public demo server at
45 Authentication Full Demo Script Integrated example combining Basic, API Key, JWT, Cookies, claims & policies.
46 Responses Text & JSON Script Use Write-KrTextResponse for plain UTF-8 text and Write-KrJsonResponse for structured object data.
47 Responses Structured (XML / YAML / CSV) Script Return alternative serializations for interoperability, configuration and exports.
48 Responses Binary & Stream Script Use these when returning non-text payloads, large files, or custom generated data.
49 Responses HTML Templates & Files Script Render dynamic HTML or return files with proper headers.
50 Responses Special Formats (BSON / CBOR) Script Use Write-KrBsonResponse and Write-KrCborResponse for compact binary object encodings, ideal for IoT,
51 Responses Redirects Script Send 3xx status and a Location header using Write-KrRedirectResponse.
52 Responses Errors Script Use Write-KrErrorResponse for consistent failure payloads.
53 Responses Caching & Revalidation Script Combine Add-KrCacheResponse (Cache-Control directives) with Test-KrCacheRevalidation (ETag / Last-Modified) for efficient conditional requests.
54 Responses Content Negotiation Script Write-KrResponse provides content negotiation and automatic format selection based on the client’s Accept header.
55 Responses Low-Level Response Stream Script Direct manipulation of $Context.Response.Body stream for scenarios requiring manual control over response writing.
56 OpenApi Hello World Script Create a simple OpenAPI 3.1 specification with a single greeting endpoint.
57 OpenApi Component Schemas Script Define reusable request and response schemas using PowerShell classes decorated with OpenAPI attributes.
58 OpenApi RequestBody Components Script Create reusable request body components that can be shared across multiple endpoints.
59 OpenApi Parameter Components Script Create reusable parameter components for query strings, path variables, headers, and cookies.
60 OpenApi Response Components Script Create reusable response components for consistent response structures across multiple endpoints.
61 OpenApi Complete Components Script Combine request body and response components in a complete API with validation and error handling.
62 OpenApi Tags and External Docs Script Group operations with tags and attach external documentation links to both the document and specific routes.
63 OpenApi Document Information Script Populate OpenAPI document metadata including title, version, summary, terms of service, contact, license, and server list.
64 OpenApi Component Headers Script Demonstrates how to define reusable header components for OpenAPI responses.
65 OpenApi Component Links Script Demonstrates how to define reusable link components to describe relationships between operations.
66 OpenApi Component Callbacks Script Demonstrates how to define reusable callback components for asynchronous operations.
67 OpenApi WebHooks Script Demonstrates how to define top-level WebHooks in the OpenAPI document.
68 OpenApi Examples Script Demonstrates OpenAPI example components plus inline examples applied to requests, responses, and parameters.
69 OpenApi Swagger Petstore Script Implementation of the classic Swagger Petstore example (OpenAPI 3.1) using Kestrun.
70 OpenApi Redocly Museum API Script A comprehensive example implementing the Redocly Museum API specification using Kestrun.
71 OpenApi Multiple OpenAPI Documents Script Shows how to serve multiple OpenAPI documents (a default document plus a separate webhook document) from the same Kestrun server.
72 OpenApi Product Search with HTTP QUERY (OpenAPI 3.2) Script Demonstrates the OpenAPI 3.2 HTTP QUERY method with structured request body filters, pagination parameters, and response content negotiation.
73 OpenApi SSE (OpenAPI) Script Document a Server-Sent Events (SSE) endpoint (text/event-stream) using OpenAPI.
74 OpenApi SSE Broadcast (OpenAPI) Script Document a broadcast SSE endpoint (text/event-stream) and a JSON broadcast trigger API using OpenAPI.
75 OpenApi SignalR (OpenAPI) Script Document SignalR-adjacent HTTP routes (that trigger hub broadcasts) using OpenAPI.
76 OpenApi XML Modeling Script Demonstrate OpenAPI 3.2 XML modeling with attributes, namespaces, and wrapped arrays using the OpenApiXml attribute.
77 OpenApi RFC 6570 Variable Mapping Script Document OpenAPI 3.2 RFC 6570 path expressions and map ASP.NET Core route values into RFC6570 variables for multi-segment paths.
78 OpenApi Additional and Pattern Properties Script Model dynamic key/value objects using additionalProperties and patternProperties.
79 OpenApi Custom Error Handler Script Use OpenAPI error schemas with a custom PowerShell runtime error response script for OpenAPI routes.
80 Razor Razor Pages Quickstart Script Serve Razor Pages where each .cshtml can have an optional sibling .cshtml.ps1 script that builds a per-request model.
81 Razor Razor Pages with Antiforgery Script Protect unsafe endpoints using cookie + header antiforgery tokens, and expose a token endpoint.
82 Scheduler Scheduling Quickstart Script Enable the scheduler, register a couple of jobs, and expose diagnostic routes.
83 Scheduler Scheduling with CRON Script Run jobs using 6-field CRON expressions with seconds precision.
84 Scheduler Scheduling Report Script Expose an endpoint that returns the aggregated schedule report, optionally in a specific time zone.
85 Server Configuration Server Limits Script Fine‑tune resource & safety thresholds using Set-KrServerLimit.
86 Server Configuration Server Options Script Configure runtime behaviors (headers, compression, runspaces) with Set-KrServerOptions.
87 Lifecycle Start/Stop Patterns Script Control server lifecycle: blocking vs non‑blocking, programmatic shutdown.
88 Lifecycle Full Server Demo Script Run an integrated demo server with multiple endpoints, basic routes, and clean start/stop.
89 Middleware Antiforgery Protection Script Protect state‑changing endpoints (POST/PUT/PATCH/DELETE) from Cross-Site Request Forgery by validating a token that is bound to a user session cookie.
90 Middleware Response Compression Script Reduce payload size (bandwidth + latency) for text-based responses by enabling
91 Middleware HTTPS Redirection Script Force HTTP traffic to upgrade to HTTPS with a configurable redirect status code and optional explicit HTTPS port.
92 Middleware HTTPS Strict Transport Security (HSTS) Script HTTP Strict Transport Security (HSTS) is a web security policy mechanism that helps protect websites against
93 Middleware SignalR Script Add real-time, bidirectional communication to your server for live events, progress, and notifications using SignalR.
94 Middleware Host Filtering Script Restrict which Host headers are allowed to reach your app.
95 Middleware Forwarded Headers Script Honor X-Forwarded-* headers from a reverse proxy to reflect the original client IP, scheme, and host.
96 Middleware CORS Script Configure Cross-Origin Resource Sharing (CORS) policies to control browser access from different origins.
97 Middleware SSE Script Stream real-time server events to browsers using Server-Sent Events (SSE).
98 Middleware SSE Broadcast Script Keep an SSE connection open and broadcast events to all connected clients.
99 Middleware Request Decompression Script Accept request bodies compressed with Content-Encoding (for example gzip) by enabling the Request Decompression middleware.
100 Health Health Quickstart Script Expose /healthz and aggregate basic probes (script + HTTP) into a single JSON document for liveness / readiness checks.
101 Health Script Probe Script Demonstrates a standalone PowerShell script probe measuring latency and producing custom metrics.
102 Health HTTP Probe Script Shows using the built‑in HTTP probe to call an internal route and fold its success/failure into the health aggregate.
103 Health Process Probe Script Executes an external process (dotnet --info) and reports its success & duration.
104 Health C# Inline Probe Script Illustrates using the C# inline capability to craft a probe in code when PowerShell alone is insufficient or you want direct .NET API access.
105 Health Disk Probe Script Demonstrates the built‑in disk space probe (auto‑registered) and how to override it with custom thresholds.
106 Health Health Response Format Script Demonstrates configuring health endpoints with Auto response format for content negotiation
107 Status Code Pages Default Status Code Pages Script Enable built-in error pages so 404, 500, and similar responses return consistent content.
108 Status Code Pages Custom Options Script Configure StatusCodePages behavior via options such as content type, formats, redirects, or re-execution.
109 Status Code Pages Custom Handler (PowerShell) Script Handle status codes with a PowerShell ScriptBlock that logs and returns a JSON error payload.
110 Status Code Pages Custom Handler (C# Inline) Script Handle status codes with an inline C# snippet that composes a JSON payload and writes the response.
111 Status Code Pages Content Format Script Customize the error content type and HTML body with external templates and variables.
112 Status Code Pages Redirects Script Redirect error responses to friendly routes and render details via templates.
113 Status Code Pages Re-execute Script Re-execute the pipeline using alternate routes to generate friendly error pages while keeping the original URL.
114 Status Code Pages Common Status Codes Script Try common HTTP status codes (401/403/404/405/415/400/422/200/201/204) on a small set of routes.
115 Exception Handling Exception Handling Path Script Re-execute the pipeline to a fixed error path when an unhandled exception occurs.
116 Exception Handling VB.NET Handler Script Handle exceptions using a VB.NET middleware handler for consistent JSON across routes.
117 Exception Handling C# Inline Handler Script Handle exceptions with a C# inline handler.
118 Exception Handling ProblemDetails Fallback Script Return RFC 7807 ProblemDetails for unhandled exceptions, ideal for API clients.
119 Exception Handling Developer Exception Page Script Show rich error details during development.
120 Sessions Basic Sessions Script Use cookie-based session state to persist small key-value data across requests (counters, user info, preferences).
121 Sessions Sessions with Redis Script Use StackExchange.Redis as the distributed cache backing for ASP.NET Core session state.
122 Sessions Sessions with SQL Server Script Use SQL Server as the distributed cache backing for ASP.NET Core session state.
123 Tasks Basic Tasks Script Run ad-hoc scripts as background tasks with status, progress, results, cancellation, and controlled removal.
124 Localization Localization Script Serve localized responses with PowerShell-style string tables resolved per request.
125 Localization Razor Localization Script Render localized Razor pages with per-request culture resolution.
126 File and Form Uploads Basic multipart/form-data upload Script Parse a simple multipart upload with one text field and one file.
127 File and Form Uploads Multiple files (same field name) Script Accept multiple files posted under a single field name.
128 File and Form Uploads application/x-www-form-urlencoded forms Script Parse classic HTML form posts with urlencoded bodies.
129 File and Form Uploads multipart/mixed ordered parts Script Parse ordered multipart payloads where part order matters.
130 File and Form Uploads Nested multipart/mixed Script Handle a single nested multipart/mixed payload inside an ordered multipart body.
131 File and Form Uploads Request-level compression Script Enable ASP.NET Core RequestDecompression middleware for gzip request bodies.
132 File and Form Uploads Part-level compression Script Decompress individual multipart parts using per-part Content-Encoding.
133 File and Form Uploads OpenAPI: basic multipart upload Script Document a basic multipart/form-data upload with OpenAPI annotations.
134 File and Form Uploads OpenAPI: multiple files Script Describe multiple files under the same field name with OpenAPI.
135 File and Form Uploads OpenAPI: urlencoded forms Script Document application/x-www-form-urlencoded payloads with OpenAPI.
136 File and Form Uploads OpenAPI: multipart/mixed Script Document ordered multipart/mixed payloads with OpenAPI.
137 File and Form Uploads OpenAPI: nested multipart Script Document nested multipart/mixed payloads with OpenAPI.
138 File and Form Uploads OpenAPI: request-level compression Script Document request-compressed multipart uploads with OpenAPI.
139 File and Form Uploads OpenAPI: part-level compression Script Document per-part Content-Encoding with OpenAPI annotations.
140 File and Form Uploads OpenAPI: file hash upload Script Upload a binary file and return MD5/SHA1/SHA256/SHA384/SHA512 hashes with OpenAPI annotations.
141 File and Form Uploads Form rules: file hash upload Script Upload a binary file using New-KrFormPartRule and return MD5/SHA1/SHA256/SHA384/SHA512 hashes.

Static chapters and scripts are all linked directly above for quick navigation.


Table of contents