Custom 404 with HttpListener

I have a problem with HttpListener, it works fine (including returning 404), but if I write something to the output stream (to return a custom html for 404), even if I set the status code = 404 firebug displays the status 200 ok as soon as i remove the custom html it sees 404 as expected.

How can I get 404 if I uncomment the two commented lines, I get the HTML that I want to display but 200, while I expect 404:

//var buffer = System.Text.Encoding.UTF8.GetBytes("<html><head></head><body><h1>404 not found</h1></body></html>"); //ctx.Response.OutputStream.Write(buffer, 0, buffer.Length); ctx.Response.StatusCode = 404; 
+4
source share
1 answer

Since the HTTP protocol requires that the status code be sent before the content as soon as you write to the output stream, the status 200 is automatically sent for you, followed by everything that you write in the stream. If you try to set the status code after writing to the output stream, it is already too late.

+5
source

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


All Articles