return a text response from a http server in csharp

You can return a text response from an HTTP server in C# using the HttpListenerResponse class. Here's an example code snippet:

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

class Program {
    static void Main(string[] args) {
        // Create a HttpListener object and start listening for incoming requests
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();
        
        Console.WriteLine("Listening for incoming requests...");
        
        // Handle incoming requests
        while (true) {
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            
            if (request.HttpMethod == "GET") {
                // Return a text response
                byte[] buffer = Encoding.UTF8.GetBytes("Hello, world!");
                response.ContentType = "text/plain";
                response.ContentLength64 = buffer.Length;
                response.OutputStream.Write(buffer, 0, buffer.Length);
            }
            
            response.Close();
        }
        
        // Stop listening for incoming requests
        listener.Stop();
    }
}
1165 chars
35 lines

In this example, we're creating an HttpListener object that listens for incoming requests on http://localhost:8080/. When a request is received, we're checking if the HTTP method is GET. If it is, we're returning a text response with the content Hello, world!.

To return a text response, we're first converting the text to a byte array using Encoding.UTF8.GetBytes(). We're setting the ContentType property of the HttpListenerResponse object to "text/plain" to indicate that we're sending plain text. We're also setting the ContentLength64 property to the length of the buffer in bytes. Finally, we're writing the buffer to the output stream of the HttpListenerResponse object using response.OutputStream.Write().

Once the response has been sent, we're calling the Close() method of the HttpListenerResponse object to close the response and clean up any resources used.

gistlibby LogSnag