return a html response from a http server in csharp

To return an HTML response from an HTTP server in C#, you can use the HttpListener class in .NET. Here is an example that shows how to create a basic HTTP server that returns an HTML response:

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

class Program {
    static void Main(string[] args) {
        // Create a new HttpListener
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8000/");

        // Start listening for incoming requests
        listener.Start();
        
        Console.WriteLine("Listening on http://localhost:8000/");
        
        while (true) {
            HttpListenerContext context = listener.GetContext();
            
            // Generate the HTML content to be returned
            string htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
            
            // Convert the HTML content to a byte array
            byte[] htmlBytes = Encoding.UTF8.GetBytes(htmlContent);
            
            // Set the content type to "text/html"
            context.Response.ContentType = "text/html";
            
            // Set the content length to the length of the HTML byte array
            context.Response.ContentLength64 = htmlBytes.Length;
            
            // Write the HTML byte array to the response stream
            context.Response.OutputStream.Write(htmlBytes, 0, htmlBytes.Length);
            
            // Close the response
            context.Response.Close();
        }
    }
}
1325 chars
39 lines

In this example, we create an HttpListener and add a prefix for the URL we want to listen on (http://localhost:8000/). We then start listening for incoming requests and loop indefinitely. When a request is received, we generate the HTML content we want to return, convert it to a byte array, set the content type to text/html, set the content length to the length of the byte array, write the byte array to the response stream, and close the response.

gistlibby LogSnag