create a http server and read the request body as json and return a json response in csharp

To create an Http server in C#, you can use the built-in HttpListener class. Here's an example:

main.cs
using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

public class MyHttpServer {
    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;

            if (request.HttpMethod == "POST") {
                using (var reader = new StreamReader(request.InputStream)) {
                    var requestBody = reader.ReadToEnd();
                    var requestData = JsonConvert.DeserializeObject(requestBody);
                    // process requestData and create a response
                    var responseData = new { Message = "Hello" };
                    var responseBody = JsonConvert.SerializeObject(responseData);
                    response.ContentType = "application/json";
                    response.ContentEncoding = Encoding.UTF8;
                    response.StatusCode = 200;
                    using (var writer = new StreamWriter(response.OutputStream)) {
                        writer.Write(responseBody);
                    }
                }
            } else {
                response.StatusCode = 405;
            }

            response.Close();
        }
    }
}
1448 chars
41 lines

This code listens for HTTP requests on http://localhost:8080/ and expects JSON data to be sent in the request body. It parses the JSON data using Newtonsoft.Json, processes it, and creates a JSON response. The response is sent with a content type of application/json and a status code of 200. If the request method is not POST, a 405 Method Not Allowed response is sent.

gistlibby LogSnag