create a http server and read the request body as html in csharp

Here's an example of how to create an HTTP server in C# that reads the request body as HTML:

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("Listening...");

        while (true)
        {
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            Console.WriteLine($"Request method: {request.HttpMethod}");
            Console.WriteLine($"Request URL: {request.Url}");

            if (request.HasEntityBody)
            {
                Stream body = request.InputStream;
                Encoding encoding = request.ContentEncoding;
                StreamReader reader = new StreamReader(body, encoding);
                string html = reader.ReadToEnd();
                Console.WriteLine($"HTML body: {html}");
            }

            HttpListenerResponse response = context.Response;
            string responseString = "<html><body><h1>Hello, world!</h1></body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
    }
}
1379 chars
41 lines

In this example, we create an HttpListener that listens for requests on http://localhost:8080/. When a request is received, we get the context and request objects. We check if the request has an entity body (i.e., a request with a POST or PUT method that sends data in the request body). If it does, we read the request body using a StreamReader and print it to the console.

We then create an HttpListenerResponse and set the response body to a simple HTML string. Finally, we write the response to the output stream and close it. This is just a basic example, but it can be easily modified to handle more complex requests and responses.

related categories

gistlibby LogSnag