return a json response from a http server in csharp

Here is a sample code snippet to return a JSON response from an HTTP server in C#:

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

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

        while (true)
        {
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;

            if (request.HttpMethod == "GET")
            {
                string responseString = JsonConvert.SerializeObject(new { message = "Hello, World!" });

                HttpListenerResponse response = context.Response;
                response.ContentType = "application/json";
                response.ContentEncoding = System.Text.Encoding.UTF8;
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
        }
    }
}
1142 chars
36 lines

In this example, we are using HttpListener to listen for incoming HTTP requests. When a GET request is received, we serialize a simple message using JsonConvert.SerializeObject and write it to the response stream as a JSON string. Finally, we set the content type to application/json and send the response back to the client.

gistlibby LogSnag