.NET API Reference

System.Net.HttpListenerContext Class

The HttpListenerContext class provides access to request and response information used by the HttpListener class to process HTTP requests.

Overview
Authors

Syntax

public sealed class HttpListenerContext

Inheritance

System.Object → System.Net.HttpListenerContext

Microsoft

Properties

NameTypeDescription
RequestHttpListenerRequestGets the request object that contains information about the client's request.
ResponseHttpListenerResponseGets the response object used to construct and send a response to the client.
UserIPrincipalGets or sets the authenticated user for this request.
ConnectionHttpListenerConnectionProvides details about the underlying TCP connection.

Methods

NameReturnsDescription
Abort()voidImmediately aborts processing of the request and closes the connection.
Close()voidFinishes response processing and releases resources.

Remarks

The HttpListenerContext instance is created each time HttpListener.GetContext() or HttpListener.BeginGetContext() returns a new request. It encapsulates both the incoming request and the outgoing response, making it easier to handle them together.

Typical usage involves reading from Request.InputStream and writing to Response.OutputStream. Be sure to close or dispose the streams when finished to free the underlying network resources.

Example

using System; using System.Net; using System.Text; class SimpleServer { static void Main() { var listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); Console.WriteLine("Listening..."); while (true) { var context = listener.GetContext(); // HttpListenerContext var request = context.Request; var response = context.Response; string responseString = $"<html><body>Hello from {request.Url}</body></html>"; byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; response.OutputStream.Write(buffer, 0, buffer.Length); response.OutputStream.Close(); } } }

See also