Home > Uncategorized > Tiny C# code to test webhooks with NGrok

Tiny C# code to test webhooks with NGrok

TL;DR; Here is the github repo: https://github.com/infiniteloopltd/MiniServer/

If you need to test webhooks, it can be sometimes awkward, since you have to deploy your webhook handling code to a server, and once there, you can’t debug it. Running it on localhost, then the remote service can’t reach it.

This is where NGrok comes in handy, you can use it to expose (Temporarily) a local website – including your webhook handler, and then use the URL from NGgok as the webhook endpoint. Once it’s working locally, you can deploy it to the server, for more testing.

Here I wrote a tiny webserver that just prints to screen what it HTTP posted / Get’d to it,

static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8080/");
            listener.Start();
            Console.WriteLine("Listening for requests on http://localhost:8080/ ...");

            while (true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                // Log the request method (GET/POST)
                Console.WriteLine("Received {0} request for: {1}", request.HttpMethod, request.Url);

                // Log the headers
                Console.WriteLine("Headers:");
                foreach (string key in request.Headers.AllKeys)
                {
                    Console.WriteLine("{0}: {1}", key, request.Headers[key]);
                }

                // Log the body if it's a POST request
                if (request.HttpMethod == "POST")
                {
                    using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                    {
                        string body = reader.ReadToEnd();
                        Console.WriteLine("Body:");
                        Console.WriteLine(body);
                    }
                }

                // Respond with a simple HTML page
                HttpListenerResponse response = context.Response;
                string responseString = "<html><body><h1>Request Received</h1></body></html>";
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }

Then the server is exposed via NGrok with

ngrok http 8080 --host-header="localhost:8080" 

I’ve tried similar code with CloudFlare tunnels, but it wasn’t as easy to set up as NGrok.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment