The HTTP response and how it relates to System.Net.HttpListener
This is part 3 of the sequel to "How to build a web based user interaction layer in C#". In this post, I will discuss how to send a HTTP response back to the client.
In part 1, we learn how we can get an instance of the System.Net.HttpListenerContext class whenever a client sends a HTTP request.
In part 2, we learn how we can process the HTTP request received from the client in your C# program.
Continuing the sequel
An instance of the System.Net.HttpListenerResponse class will be available via the Response property from the same HttpListenerContext
instance that was received from the HttpListener
instance when a client sends a HTTP request.
HttpListenerResponse serverResponse = context.Request;
We can use the HttpListenerResponse
instance to send build a HTTP response to send back to the client.
The HTTP status code
The HTTP status code is a way to reflect the outcome of processing the HTTP request that the client sent. For instance, to indicate that a HTTP request is successfully processed, we set 200 to the StatusCode
property of the HttpListenerResponse
instance. We can also use the OK
value from the System.Net.HttpStatusCode enumeration to do that.
serverResponse.StatusCode = (int) System.Net.HttpStatusCode.OK;
The content type
The ContentType property of the HttpListenerResponse
class can be set to let the client know what kind of content is contained in the HTTP response body.
// Indicate that the response body contain a HTML document serverResponse.ContentType = "text/html";
The length of the content
The ContentLength64
property of the HttpListenerResponse
class describe the size of the HTTP response body that the client will be receiving, in bytes.
// Set the size of the HTML file as the content length // of the HTTP response serverResponse.ContentLength64 = htmlFileInfo.Length;
The content
With the OutputStream
property of the HttpListenerResponse instance, you can fill the contents for the HTTP response body.
System.IO.Stream serverResponseOutput = serverResponse.OutputStream;
Send the response back to the client
After you are done with filling up the HttpListenerResponse
instance with information for the HTTP response, you need to call the Close
method to send it back to the client.
serverResponse.Close();
Next in the line
This concludes part 3 of "How to build a web based user interaction layer in C#".
In part 4, I will sum up the sequel with how to implement a mechanism for serving HTTP requests in C#.
Further reading elsewhere
What I had mentioned in this post is probably enough for your C# program to construct HTTP responses back to clients in most situation. If your program needs to furnish more information in the HTTP responses to clients, check out the MSDN reference for the System.Net.HttpListenerResponse
class.