return a json response from a http server with a specific status code in csharp

Here is an example code snippet that demonstrates how to return a JSON response with a specific status code from an HTTP server in C#:

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

// ... Your code here ...

HttpListenerContext context = listener.GetContext(); // Get the context object from HttpListener

// ... Your code here ...

JsonObject responseJson = new JsonObject(); // Create your JSON response object
responseJson.Add("message", "Hello, World!");  // Add any properties to your JSON response

byte[] buffer = JsonSerializer.SerializeToUtf8Bytes(responseJson); // Serialize your JSON response to a byte array

context.Response.StatusCode = (int)HttpStatusCode.OK; // Set a specific status code on the response
context.Response.ContentType = "application/json"; // Set the content type on the response
context.Response.ContentLength64 = buffer.Length; // Set the content length of the response

Stream output = context.Response.OutputStream; // Get the output stream of the HttpListenerResponse object
output.Write(buffer, 0, buffer.Length); // Write the response to the output stream
output.Close(); // Close the output stream
1031 chars
24 lines

In this example, we first create a JsonObject to represent our JSON response. We then serialize this object to a byte array using the JsonSerializer.SerializeToUtf8Bytes() method.

Next, we set the status code of the HttpListenerResponse object using the context.Response.StatusCode property. We set the content type of the response using the context.Response.ContentType property, and we set the content length using the context.Response.ContentLength64 property.

Finally, we get the output stream from the HttpListenerResponse object and write the serialized JSON data to it using the Stream.Write() method. We then close the output stream.

Note: This example code assumes that you are using the HttpListener class in C# to create an HTTP server. If you are using a different HTTP server library or framework, the code may be different.

gistlibby LogSnag