create a http server and parse cookies and return a json response in csharp

Here's an example of how to create an HTTP server in C# using the .NET framework that parses cookies and returns a JSON response:

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

class HttpServer {
    private HttpListener _listener;

    public HttpServer(int port) {
        _listener = new HttpListener();
        _listener.Prefixes.Add($"http://localhost:{port}/");
    }

    public async void Start() {
        _listener.Start();
        Console.WriteLine($"Server started at: {_listener.Prefixes}");

        while (true) {
            HttpListenerContext context = await _listener.GetContextAsync();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            // Parse cookies
            CookieCollection cookies = request.Cookies;

            // Create a JSON object
            var responseObject = new {
                message = "Hello, world!",
                cookies = cookies
            };

            // Serialize the object to JSON
            string json = JsonSerializer.Serialize(responseObject);

            // Set response headers
            response.ContentType = "application/json";
            response.ContentEncoding = System.Text.Encoding.UTF8;
            
            // Write the JSON data to the response
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(json);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
    }
}

class Program {
    static void Main(string[] args) {
        HttpServer server = new HttpServer(8080);
        server.Start();
        Console.ReadKey();
    }
}
1650 chars
56 lines

In this example, we create an HttpServer class that listens for requests on port 8080. When a request is received, we get the request's cookies, create a JSON object that includes the message "Hello, world!" and the cookies, serialize the object to JSON, and write the JSON data to the response.

To start the server, we create an instance of the HttpServer class and call the Start method. The server will run indefinitely until the program is terminated.

related categories

gistlibby LogSnag