You can return a text response from an HTTP server in C# using the HttpListenerResponse
class. Here's an example code snippet:
main.cs1165 chars35 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