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.cs1119 chars38 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