Click here to Skip to main content
15,878,231 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear experts
I have no clue what I'm doing wrong, I hope you can enlighten me.
I'm playing with HttpListener to learn about it.

In the code shown in 'What have you tried' I experience following when I do a request 'http://localhost:8001/' by e.g. chrome:
a.) In the log I see for one browser request, I get two log entries
b.) In the browser I see incrementing the counter always by 2 for each request.

Why one and the same request is processed twice?
Btw. same happens if I take the asynch approach using httpListener.BeginGetContext and httpListener.EndGetContext

Thank you very much in advance.

What I have tried:

namespace WFATestApp
{
    public partial class FormMain : Form
    {
        BackgroundWorker bgWorker = new BackgroundWorker();
        HttpListener httpListener = new HttpListener();


        public FormMain()
        {
            InitializeComponent();

            httpListener.Prefixes.Add("http://localhost:8001/");

            bgWorker.DoWork += new DoWorkEventHandler(BgWorker_DoWork);
            bgWorker.RunWorkerAsync();
        }

        void LogMsg(String Msg)
        {
            listBoxLog.Items.Add(Msg);
            listBoxLog.SelectedIndex = listBoxLog.Items.Count - 1;
        }

        int requestCount = 0;

        private void BgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgw = sender as BackgroundWorker;
            bool cancel = false;

            httpListener.Start();

            while (!cancel)
            {
                var context = httpListener.GetContext();

                requestCount++;

                // The request
                // HttpListenerRequest request = context.Request;

                // Get response object.
                HttpListenerResponse response = context.Response;

                // Construct a response. 
                string responseString = $"<HTML><BODY> It Works! {requestCount} </BODY></HTML>";
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                
                // Write to response stream.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                
                // Close the output stream.
                output.Close();

                this.Invoke((MethodInvoker)delegate
                {
                    LogMsg("http request count: " + requestCount.ToString());
                });


                cancel = bgw.CancellationPending;
            }
            httpListener.Stop();
        }

    }
}
Posted
Updated 26-Mar-23 3:56am
v2

1 solution

Browser requires a FavIcon. If you open your Web browser tools > Network tab, and make a request, you can clearly see it.

In you app use:
C#
LogMsg($"http request {context.Request.RawUrl}  | count: {requestCount}");

Now you can see it. 😉
 
Share this answer
 
Comments
0x01AA 26-Mar-23 9:58am    
Hundred thousand thanks. I can only give my little 5 :)
Graeme_Grant 26-Mar-23 10:02am    
All good. Another way is to set a breakpoint on
requestCount++;

Then, when the breakpoint is hit, go to your immediate window and post:
context.Request


Then you will see something like:
{System.Net.HttpListenerRequest}
    AcceptTypes: {string[6]}
    ClientCertificateError: 'context.Request.ClientCertificateError' threw an exception of type 'System.InvalidOperationException'
    ContentEncoding: {System.Text.SBCSCodePageEncoding}
    ContentLength64: 0
    ContentType: null
    Cookies: {System.Net.CookieCollection}
    HasEntityBody: false
    Headers: {sec-ch-ua: "Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"
DNT: 1
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: no-cors
Sec-Fetch-Dest: image
Connection: keep-alive
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Host: localhost:8001
Referer: http://localhost:8001/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

}
    HttpListenerContext: {System.Net.HttpListenerContext}
    HttpMethod: "GET"
    InputStream: {System.IO.Stream.NullStream}
    IsAuthenticated: false
    IsLocal: true
    IsSecureConnection: false
    IsWebSocketRequest: false
    KeepAlive: true
    LocalEndPoint: {[::1]:8001}
    OriginalBlobAddress: 0x02bc6958
    ProtocolVersion: {1.1}
    QueryString: {System.Collections.Specialized.NameValueCollection}
    RawUrl: "/favicon.ico"
    RemoteEndPoint: {[::1]:63541}
    RequestBuffer: {byte[4096]}
    RequestId: 18230571318439313419
    RequestScheme: "http"
    RequestTraceIdentifier: {00000000-0000-0000-0b00-0040060000fd}
    RequestUri: {http://localhost:8001/favicon.ico}
    ServiceName: null
    TransportContext: {System.Net.HttpListenerRequestContext}
    Url: {http://localhost:8001/favicon.ico}
    UrlReferrer: {http://localhost:8001/}
    UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"
    UserHostAddress: "[::1]:8001"
    UserHostName: "localhost:8001"
    UserLanguages: {string[2]}
    m_BoundaryType: ContentLength
    m_ClientCertState: NotInitialized
    m_ClientCertificate: null
    m_ClientCertificateError: 0
    m_ConnectionId: 18230571318170877960
    m_ContentLength: 0
    m_CookedUrlHost: "localhost:8001"
    m_CookedUrlPath: "/favicon.ico"
    m_CookedUrlQuery: null
    m_Cookies: {System.Net.CookieCollection}
    m_HttpContext: {System.Net.HttpListenerContext}
    m_HttpMethod: "GET"
    m_IsDisposed: false
    m_KeepAlive: True
    m_LocalEndPoint: {[::1]:8001}
    m_Lock: {object}
    m_MemoryBlob: {System.Net.SyncRequestContext}
    m_RawUrl: "/favicon.ico"
    m_RemoteEndPoint: {[::1]:63541}
    m_RequestId: 18230571318439313419
    m_RequestStream: {System.IO.Stream.NullStream}
    m_RequestUri: {http://localhost:8001/favicon.ico}
    m_ServiceName: null
    m_SslStatus: Insecure
    m_TokenBindingVerifyMessageStatus: 0
    m_TokenBindings: null
    m_Version: {1.1}
    m_WebHeaders: {sec-ch-ua: "Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"
DNT: 1
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: no-cors
Sec-Fetch-Dest: image
Connection: keep-alive
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Host: localhost:8001
Referer: http://localhost:8001/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWeb

or go to the Locals window and expand the context variable and view the branches ... the joys of debugging
0x01AA 26-Mar-23 10:12am    
Thank you very much again.
0x01AA 26-Mar-23 10:26am    
I'm aware now I'm becoming something off topic to ask a question in a comment.
Nevertheless I do it ;) :
Is it a bad praxis to 'POST' e.g. a zip file as content type 'octet stream' to a rest service?
Graeme_Grant 26-Mar-23 13:27pm    
No ... use ContentType "application/octet-stream"
But yes, now off topic....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900