create a http server in csharp

Here's a basic example of how to create a HTTP server in C# using .NET:

main.cs
using System;
using System.IO;
using System.Net;
using System.Text;

class HttpServer
{
    static void Main(string[] args)
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();
        
        Console.WriteLine("Server started. Listening for connections...");

        while (true) 
        {
            HttpListenerContext context = listener.GetContext();
            
            string responseString = "<html><body><h1>Hello, World!</h1></body></html>";
            byte[] responseBytes = Encoding.UTF8.GetBytes(responseString);
            
            context.Response.ContentLength64 = responseBytes.Length;
            context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
            
            context.Response.Close();
        }
    }
}
863 chars
30 lines

This code listens for incoming connections on http://localhost:8080/ and responds to every request with a fixed HTML string. You can modify the response string to return dynamic content based on the request. Make sure to handle any exceptions that may arise when running the server, such as HttpListenerException.

related categories

gistlibby LogSnag