Class HttpListenerRouter
Routes HttpListenerContext instances through a NanoRoute pipeline.
Inherited Members
Namespace: NanoRoute
Assembly: NanoRoute.dll
Syntax
public sealed class HttpListenerRouter : Router<HttpListenerRouter, HttpListenerRouterConfig>
Remarks
This adapter converts incoming HttpListener traffic into the core HttpRequestMessage/HttpResponseMessage pipeline used by NanoRoute.
Examples
HttpListenerRouter router = HttpListenerRouter
.CreateBuilder()
.AddDefaultValueParsers()
.AddHandler("GET", "/health/", (context, _) => Results.Ok())
.CreateRouter();
Methods
Route(HttpListenerContext, IServiceProvider, CancellationToken)
Routes a single HttpListener request and writes the produced response.
Declaration
public Task Route(HttpListenerContext context, IServiceProvider services, CancellationToken cancellation = default)
Parameters
| Type | Name | Description |
|---|---|---|
| HttpListenerContext | context | The listener context that supplies the request and receives the response. |
| IServiceProvider | services | The service provider exposed to handlers through Services. |
| CancellationToken | cancellation | A token that can cancel request processing and response streaming. |
Returns
| Type | Description |
|---|---|
| Task | A task that completes after the router has finished writing the response. |
Remarks
Request and content headers are copied into the intermediate HttpRequestMessage. The original HttpListenerRequest is stored in OriginalRequestName on the generated request message. Response headers are copied back except for reserved HttpListenerResponse headers that must be managed by HttpListener itself. Cancellation is not translated into an HTTP error response by this adapter.
Examples
HttpListenerRouter router = HttpListenerRouter
.CreateBuilder()
.AddJsonErrorDetails()
.AddDefaultValueParsers()
.AddHandler("GET", "/hello/{name:str}/", (context, _) =>
Task.FromResult(HttpResponseMessage.Json(new
{
message = $"Hello {context.Parameters["name"]}"
})))
.CreateRouter();
await router.Route(listenerContext, services, cancellationToken);
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown when |
| ArgumentException | Thrown when the request uses an unsupported HTTP method. |
| HttpRequestException | Thrown when no handler matches the request path or a matched handler signals an HTTP failure that is not translated by middleware. |
| OperationCanceledException | Thrown when the caller cancels |