Reputation: 111
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();
}
Upvotes: 9
Views: 9894
Reputation: 41
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.
Upvotes: 4
Reputation: 37868
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:
Upvotes: 17