You can create an HTTP server and read a JSON request body in C# by using the .NET HttpListener
class.
Here is a code snippet that demonstrates how to create a simple HTTP server in C# and read the request body as JSON:
main.cs1404 chars47 lines
In this example, we create an HttpListener
object that listens on port 8080 for incoming HTTP requests. We then loop indefinitely, waiting for requests to come in. When a request arrives, we check if it is a valid JSON POST request. If so, we read the request body as a string using a StreamReader
, then deserialize the JSON into a JsonElement
object using JsonSerializer.Deserialize()
. We can then do something with the JSON as needed (in this case, just print it to the console). Finally, we send a 200 OK response back to the client.
Note that this is just a simple example to get you started. In a real-world application, you would want to handle errors, implement security mechanisms, and add more robust validation of the incoming request.
gistlibby LogSnag