9

I am using C# HttpListener class to realize some server. And here is the problem. I just want to send to client an empty response to the request like

HTTP/1.1 200 OK

or

HTTP/1.1 400 Bad Request

without any additional text. So I set status code and status description and don't write any bytes to response OutputStream - I just don't need them. Then close the response to initiate sending bytes to the client with response.Close() method. And what I get on the client side shown by Fiddler is

HTTP/1.1 200 OK

Transfer-Encoding: chunked

Server: Microsoft-HTTPAPI/2.0

Date: Sun, 25 Oct 2015 10:42:12 GMT


0

There is a workaround for Server and Date fields - HttpListener Server Header c#.

But how to remove these "Transfer-Encoding: chunked" artefact and "0" body from this response?!

Thanks to all in advance!

The code:

private void ProcessContext(HttpListenerContext aContext)
    {
        HttpListenerResponse response = aContext.Response;

        response.StatusCode = (int)HttpStatusCode.OK;
        response.StatusDescription = "OK";
        response.Close();

}
Community
  • 1
  • 1
Pavel
  • 101
  • 1
  • 2
  • 5

2 Answers2

17

This will get rid of everything but the status and the Content-Length header:

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://*:5555/");
listener.Start();
listener.BeginGetContext(ar =>
{
    HttpListener l = (HttpListener)ar.AsyncState;
    HttpListenerContext context = l.EndGetContext(ar);

    context.Response.Headers.Clear();
    context.Response.SendChunked = false;
    context.Response.StatusCode = 200;
    context.Response.Headers.Add("Server", String.Empty);
    context.Response.Headers.Add("Date", String.Empty);
    context.Response.Close();
}, listener);

and in fiddler you'll see this:

enter image description here

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
  • Thank you, Nasreddine! And is it possible to omit and "Content-Length" line. Our client waits form us just the bare "HTTP/1.1 200 OK". Don't ask why.. – Pavel Oct 25 '15 at 12:16
  • *And remove body zero length line too which is separated from the header with empty line. – Pavel Oct 25 '15 at 12:28
  • 1
    @Pavel AFAIK it's not possible to modify the response of the HttpListener down to that level of detail. You can't even inherit them to override the behavior since they're sealed – Nasreddine Oct 25 '15 at 13:06
4

Just set ContentLength64 to zero before closing response stream in order to transmit data the regular way:

response.ContentLength64 = 0;
response.OutputStream.Close();

If you flush or close response stream without setting content length to any value, data will be transmitted in chunks. And 0/r/n in your response body is actually a closing chunk.