create a http server and add a custom header to the response in csharp

To create a HTTP server in C#, you can use the HttpListener class from the System.Net namespace. Here is an example code snippet to create a simple HTTP server:

main.cs
using System;
using System.Net;

public class HttpServer
{
    private readonly string _url;
    private readonly HttpListener _listener;

    public HttpServer(string url)
    {
        _url = url;
        _listener = new HttpListener();
        _listener.Prefixes.Add(_url);
    }

    public void Start()
    {
        _listener.Start();
        Console.WriteLine($"Server started at {_url}");
        while (true)
        {
            var context = _listener.GetContext();
            var response = context.Response;
            response.AddHeader("Custom-Header", "Custom header value");
            var message = "Hello World!";
            var buffer = System.Text.Encoding.UTF8.GetBytes(message);
            response.ContentLength64 = buffer.Length;
            var output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
    }

    public void Stop()
    {
        _listener.Stop();
        _listener.Close();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var server = new HttpServer("http://localhost:8080/");
        server.Start();
        Console.WriteLine("Press any key to stop the server");
        Console.ReadKey();
        server.Stop();
    }
}
1263 chars
52 lines

The code above listens for incoming HTTP requests on http://localhost:8080/ and responds with a simple message "Hello World!". The custom header "Custom-Header" with value "Custom header value" is added to each HTTP response.

Please note that HttpListener requires administrator privileges to run on privileged endpoint addresses like port 80, so make sure to run the above code as an administrator or use a non-privileged port number for testing purpose.

gistlibby LogSnag