C # HttpListener. Send EMPTY response (without any artifacts)

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

HTTP/1.1 200 OK 

or

 HTTP/1.1 400 Bad Request 

without additional text. Therefore, I set the status code and description of the state and do not write any bytes in the response of OutputStream - I just do not need them. Then close the response to initiate sending bytes to the client using the 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 the "Server" and "Date" fields - HttpListener C # header header .

But how to remove these โ€œTransfer-Encoding: chunkedโ€ and โ€œ0โ€ attributes from this answer ?!

Thank you all in advance!

Code:

 private void ProcessContext(HttpListenerContext aContext) { HttpListenerResponse response = aContext.Response; response.StatusCode = (int)HttpStatusCode.OK; response.StatusDescription = "OK"; response.Close(); } 
+5
source share
2 answers

This will save you everything except the state 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 the violinist you will see the following:

enter image description here

+7
source

Just set ContentLength64 to zero before closing the response stream to transfer data in the usual way:

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

If you clear or close the response stream without setting the length of the content for any value, the data will be transmitted in pieces. And the 0/r/n in your response enclosure is actually a closing block.

+1
source

Source: https://habr.com/ru/post/1234465/


All Articles