Search code examples
c#.nethttplistener

How to respond some form parameters after processing request from HttpListenerContext in .net (C# )


I am working with an Httplistenr which request I am processing via HttpListenerContext.

Previously I was just sending an Ok http response with out any content, now I need to respond with a couple of parameters like Field1 = A, Field2 = B.

I have set the response.ContentType to application/x-www-form-urlencoded, but I don't know how to add the response values to the response.

My current method is

  private void ProcessRequest(HttpListenerContext context)
  {        
        if (context.Request.Headers != null && context.Request.Headers.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"Request Headers {Environment.NewLine}");
            ..
        }             

        if (context.Request.InputStream != null)
        {
            using (var body = context.Request.InputStream)
            {
                var encoding = context.Request.ContentEncoding;

                using (var reader = new StreamReader(body, encoding))
                {
                    var conentRecieved  = reader.ReadToEnd();
                    ..,
                }
            }
        }

        var response = context.Response;
        response.ContentType = "application/x-www-form-urlencoded";             
        response.StatusCode = (int)HttpStatusCode.OK;
        response.StatusDescription = "OK";
        response.ContentLength64 = 0;
        response.OutputStream.Close();
        response.Close();            
}

I know how to send json type or simple text by setting respective content type and setting the content


Solution

  • To send a string in the response body with HttpListener you either encode the string to a byte[] and use response.OutputStream.Write() and a content-length header. Or just write start writing to it with a System.IO.StreamWriter and it will internally either use buffering and a content-length header, or use chunked transfer coding.

    eg:

    var response = context.Response;
    response.ContentType = "application/x-www-form-urlencoded";
    response.StatusCode = (int)HttpStatusCode.OK;
    var responseString = "MyVariableOne=ValueOne&MyVariableTwo=ValueTwo";
    var responseBody = System.Text.Encoding.UTF8.GetBytes(responseString);
    response.ContentLength64 = responseBody.Length;
    response.OutputStream.Write(responseBody, 0, responseBody.Length);
    response.Close();