create a http server and read the request body in csharp

To create a HTTP server in C#, you can use the HttpListener class provided by the .NET framework. Here's an example code snippet that creates a simple HTTP server and reads the request body:

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

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

        while (true)
        {
            var context = listener.GetContext();
            var request = context.Request;
            var response = context.Response;

            Console.WriteLine($"Received {request.HttpMethod} request: {request.Url}");

            // Read the request body
            using (var reader = new StreamReader(request.InputStream))
            {
                var body = reader.ReadToEnd();
                Console.WriteLine($"Request body: {body}");
            }

            // Send a response
            var message = "Hello, world!";
            var buffer = System.Text.Encoding.UTF8.GetBytes(message);
            response.ContentLength64 = buffer.Length;
            response.OutputStream.Write(buffer, 0, buffer.Length);
            response.OutputStream.Close();
        }
    }
}
1119 chars
38 lines

In this code, we first create a new HttpListener object and add a prefix to specify the URL we want to listen on. Then, we start the listener and enter an infinite loop to handle incoming requests.

When a request arrives, we get its context, and then its request and response objects. We can use the request.InputStream property to read the request body as a Stream, and then wrap it in a StreamReader for easier string manipulation. The StreamReader's ReadToEnd method reads the entire body into a string variable.

Once we've read the request body, we can send our response using the response.OutputStream property. We first create a message to send, encode it as a byte array, and then write it to the output stream. Finally, we close the stream to indicate that we've finished sending the response.

Note that this is just a basic example, and there's a lot more you can do with the HttpListener class to handle advanced scenarios like authentication, SSL, and more.

gistlibby LogSnag