HTTP server with HttpListener
suggest changeThe System.Net.HttpListener class provides a built-in, lightweight HTTP server that requires no external dependencies. It is frequently used for local inter-process communication (IPC), OAuth redirect callbacks in desktop applications, embedded test mock servers, and lightweight utility tools.
1. Minimal HTTP Server Example
To start an HttpListener, add one or more prefix URIs, call Start(), and listen for incoming HttpListenerContext requests.
Important: Every prefix URI must end with a trailing forward slash (
/).
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2, Server 2003, or newer is required to use HttpListener.");
return;
}
using var listener = new HttpListener();
string prefix = "http://localhost:8080/";
listener.Prefixes.Add(prefix);
listener.Start();
Console.WriteLine($"HTTP Server listening on {prefix}...");
while (true)
{
// Blocks until a client connects
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
Console.WriteLine($"[{DateTime.Now:T}] {request.HttpMethod} {request.Url?.AbsolutePath}");
string responseString = "<html><body><h1>Hello from C# HttpListener!</h1></body></html>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentType = "text/html; charset=utf-8";
response.ContentLength64 = buffer.Length;
response.StatusCode = (int)HttpStatusCode.OK;
using (Stream output = response.OutputStream)
{
output.Write(buffer, 0, buffer.Length);
} // Closing output stream finishes the response
}
}
}
2. Asynchronous Multi-threaded HTTP Server
In real-world applications, blocking the main thread prevents processing concurrent requests. Use GetContextAsync() and Task.Run to process each request asynchronously:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class AsyncHttpServer
{
private readonly HttpListener _listener = new();
private readonly CancellationTokenSource _cts = new();
public void Start(string prefix)
{
_listener.Prefixes.Add(prefix);
_listener.Start();
Console.WriteLine($"Server started at {prefix}");
Task.Run(async () => await ListenLoopAsync(_cts.Token));
}
private async Task ListenLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested && _listener.IsListening)
{
try
{
// Await next incoming connection without blocking thread
HttpListenerContext context = await _listener.GetContextAsync();
// Process request in a background thread to allow concurrent handling
_ = Task.Run(() => HandleRequestAsync(context), token);
}
catch (HttpListenerException) when (token.IsCancellationRequested)
{
break; // Normal shutdown
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error accepting connection: {ex.Message}");
}
}
}
private async Task HandleRequestAsync(HttpListenerContext context)
{
HttpListenerRequest req = context.Request;
HttpListenerResponse res = context.Response;
try
{
string path = req.Url?.AbsolutePath ?? "/";
if (req.HttpMethod == "GET" && path == "/api/status")
{
string json = "{\"status\":\"healthy\",\"uptimeSeconds\":" + Environment.TickCount64 / 1000 + "}";
await SendJsonResponseAsync(res, json, HttpStatusCode.OK);
}
else
{
res.StatusCode = (int)HttpStatusCode.NotFound;
byte[] notFoundMsg = Encoding.UTF8.GetBytes("404 Not Found");
res.ContentLength64 = notFoundMsg.Length;
await res.OutputStream.WriteAsync(notFoundMsg, 0, notFoundMsg.Length);
}
}
catch (Exception ex)
{
res.StatusCode = (int)HttpStatusCode.InternalServerError;
Console.Error.WriteLine($"Request handler error: {ex.Message}");
}
finally
{
res.OutputStream.Close();
}
}
private static async Task SendJsonResponseAsync(HttpListenerResponse res, string json, HttpStatusCode status)
{
byte[] buffer = Encoding.UTF8.GetBytes(json);
res.StatusCode = (int)status;
res.ContentType = "application/json; charset=utf-8";
res.ContentLength64 = buffer.Length;
await res.OutputStream.WriteAsync(buffer, 0, buffer.Length);
}
public void Stop()
{
_cts.Cancel();
_listener.Stop();
_listener.Close();
}
}
3. Handling POST Requests and Reading the Request Body
To receive JSON or form data, read from request.InputStream:
if (request.HttpMethod == "POST" && request.Url?.AbsolutePath == "/api/items")
{
using var reader = new StreamReader(request.InputStream, request.ContentEncoding);
string requestBody = await reader.ReadToEndAsync();
Console.WriteLine($"Received POST body: {requestBody}");
// Return 201 Created
response.StatusCode = (int)HttpStatusCode.Created;
response.ContentType = "application/json";
byte[] responseBytes = Encoding.UTF8.GetBytes("{\"result\":\"item received\"}");
response.ContentLength64 = responseBytes.Length;
await response.OutputStream.WriteAsync(responseBytes, 0, responseBytes.Length);
}
4. Reading Query Parameters and Request Headers
The HttpListenerRequest object exposes query parameters and headers via standard collections:
// Reading query string: http://localhost:8080/search?q=csharp&limit=10
string? searchQuery = request.QueryString["q"];
string? limitStr = request.QueryString["limit"];
// Reading headers
string? userAgent = request.Headers["User-Agent"];
string? authHeader = request.Headers["Authorization"];
5. Permissions and Configuration on Windows
On Windows, HttpListener is backed by the kernel driver http.sys.
- Binding to
http://localhost:8080/orhttp://127.0.0.1:8080/can be executed by standard, non-elevated user accounts. - Binding to external hostnames or wildcards (e.g.
http://*:8080/orhttp://+:8080/) requires administrator privileges or a URL reservation registered withnetsh:
netsh http add urlacl url=http://+:8080/ user=EVERYONE
6. HttpListener vs. ASP.NET Core (Kestrel)
| Feature | System.Net.HttpListener |
ASP.NET Core Minimal APIs / Kestrel |
|---|---|---|
| Dependencies | None (Built into Base Class Library) | Requires ASP.NET Core runtime / NuGet |
| Complexity | Low (single-file utility or tool) | Moderate to High (full web framework) |
| Routing & Middleware | Manual path matching | Built-in routing, DI, middleware pipeline |
| Throughput & Scale | Good for lightweight tools and mocks | Industry-leading high-concurrency performance |
| Best For | Desktop app redirects, unit test mocks, local IPC | Enterprise APIs, web services, microservices |