System.Net.HttpListener Class
Provides a simple, programmable HTTP server that you can use to listen for and respond to HTTP requests. This class is part of the .NET Framework's networking namespace.
HttpListener
allows applications to be built that listen for incoming HTTP requests. It is a powerful tool for creating lightweight web servers, microservices, or APIs directly within your .NET application.
Summary
The HttpListener
class provides the core functionality for creating an HTTP server. You can specify a URI prefix that the listener will bind to, and then it will receive and process incoming HTTP requests.
Key features include:
- Listening for HTTP requests on specified prefixes.
- Accessing request details like headers, URL, method, and body.
- Constructing and sending HTTP responses with status codes, headers, and content.
- Handling asynchronous operations for efficient request processing.
Members
-
HttpListener()
public HttpListener()
Initializes a new instance of the
HttpListener
class. -
Prefixes
public HttpListenerPrefixCollection Prefixes { get; }
Gets a collection of the URI prefixes that the listener is listening for.
-
IsListening
public bool IsListening { get; }
Gets a value that indicates whether the listener is currently accepting requests.
-
Start()
public void Start()
Starts the listener, enabling it to accept incoming HTTP requests.
-
Stop()
public void Stop()
Stops the listener from accepting new requests and closes all current connections.
-
GetContext()
public HttpListenerContext GetContext()
Waits for an incoming request and returns it.
-
BeginGetContext()
public IAsyncResult BeginGetContext(AsyncCallback requestCallback, object state)
Starts an asynchronous operation to listen for an incoming request.
-
EndGetContext()
public HttpListenerContext EndGetContext(IAsyncResult asyncResult)
Completes an asynchronous operation to listen for an incoming request.
Example Usage
This example demonstrates how to create a simple HTTP listener that responds to requests with a "Hello, World!" message.
using System;
using System.Net;
using System.Text;
public class SimpleHttpServer
{
public static void Main(string[] args)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("HttpListener is not supported on this platform.");
return;
}
// URI prefixes to listen on
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Prefixes.Add("http://127.0.0.1:8080/");
try
{
listener.Start();
Console.WriteLine("Listening for requests on http://localhost:8080/ ...");
while (true)
{
// Blocks until a request is received.
HttpListenerContext context = listener.GetContext();
// Process the request
HttpListenerRequest request = context.Request;
Console.WriteLine($"Received request: {request.HttpMethod} {request.Url}");
HttpListenerResponse response = context.Response;
string responseString = "Hello, World!
";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
response.ContentType = "text/html";
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
if (listener.IsListening)
{
listener.Stop();
Console.WriteLine("Listener stopped.");
}
}
}
}