---
title: "Integrate ngrok into ASP.NET Core startup and automatically update your webhook URLs"
excerpt: "Learn to integrate ngrok into ASP.NET Core's startup process to create secure public tunnels and automatically handle Twilio's webhooks with a single command"
publishDate: "2022-02-15T00:00:00"
createDate: "2022-02-15T23:33:56.363"
updateDate: "2022-02-17T05:05:03.567"
category: "dotnet"
categoryName: ".NET"
tags: [".NET","ASP.NET","ASP.NET Core",".NET Core","Minimal API","ngrok","Twilio","webhooks"]
permalink: "/blog/dotnet/integrate-ngrok-into-aspdotnet-core-startup-and-automatically-update-your-webhook-urls"
canonical: "https://www.twilio.com/en-us/blog/integrate-ngrok-into-aspdotnet-core-startup-and-automatically-update-your-webhook-urls"
image: {"src":"/media/zukb5tq0/integrate-ngrok-into-asp-net-core-update-your-webhook-urls-canonical.png","focalPoint":{"left":0.5,"top":0.5},"crops":[{"alias":"Banner","width":1120,"height":400,"coordinates":{"x1":0,"y1":0.20974201837874687,"x2":0,"y2":0.09901374198991679}}]}
imageAlt: "Integrate ngrok into ASP.NET Core & update your webhook URLs"
imageBackgroundColor: "#fff"
thumbnailImage: {"src":"/media/tfxb3k4r/ngrok-square.png","focalPoint":{"left":0.5,"top":0.5},"crops":[{"alias":"thumbnail","width":250,"height":250,"coordinates":null}]}
thumbnailImageAlt: "ngrok logo"
metaTitle: "Integrate ngrok into ASP.NET Core startup and automatically update your webhook URLs"
metaDescription: "Learn to integrate ngrok into ASP.NET Core's startup process to create secure public tunnels and automatically handle Twilio's webhooks with a single command"
ogTitle: "Integrate ngrok into ASP.NET Core startup and automatically update your webhook URLs"
ogDescription: "Learn to integrate ngrok into ASP.NET Core's startup process to create secure public tunnels and automatically handle Twilio's webhooks with a single command"
ogImage: {"src":"/media/1g5k1kjf/integrate-ngrok-into-asp-net-core-update-your-webhook-urls-canonical.png","focalPoint":{"left":0.5,"top":0.5},"crops":[{"alias":"OpenGraph","width":1200,"height":630,"coordinates":null}]}
ogImageAlt: "Integrate ngrok into ASP.NET Core & update your webhook URLs"
relatedPostKeys: ["29b547ac5a044a01972a0f963879e85f","5352c97778f64df68477e6a0715df6c0","1710543d71f748eba82e9c6891718211","99831c3f1722477fa6329b6a946bd961"]
noIndex: false
noFollow: false
sitemapExclude: true
source: {"nodeId":1589,"contentKey":"ab193d2f0bb34914b79f2d24de60013c","sortOrder":126}
---


**This blog post was written for [Twilio](https://www.twilio.com/) and [originally published at the Twilio blog](https://www.twilio.com/blog/integrate-ngrok-into-aspdotnet-core-startup-and-automatically-update-your-webhook-urls).**





When you are developing web applications on your local machine, you sometimes need your application to be reachable from the internet. One of the most common reasons to do this is to develop <a href="https://www.twilio.com/docs/usage/webhooks">webhooks</a>. 





Webhooks are a way to be notified by an external service when an event has occurred. Instead of you sending an HTTP request to that service, the service sends an HTTP request to your public web service. 


To develop webhooks locally, you can use a tunnel service like [ngrok](https://ngrok.com/) which creates a tunnel between your local network and the internet. However, when you're using ngrok's free plan, ngrok will create a random, public URL anytime you restart your tunnel. This means that you need to update your webhooks with the new URL anytime it changes. If updating your webhook URLs takes a bunch of clicks and keystrokes, this can be quite a hassle.

Luckily, you can avoid the repetitive work by automating this! In this tutorial, you'll learn how to automatically start ngrok when your ASP.NET Core application starts. Then, you'll learn how to grab the random ngrok URL and use the URL to configure Twilio's webhooks automatically.

## Prerequisites {#prerequisites}

You will need these items to follow along:


-   An OS that supports .NET (Windows/macOS/Linux)
-   [.NET 6 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/6.0)
-   A code editor or IDE (Recommended: VS Code with [the C# plugin](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp), [Visual Studio](https://visualstudio.microsoft.com/), or [JetBrains Rider](https://www.jetbrains.com/rider/))
-   The [Ngrok CLI](https://ngrok.com/download)
-   A free [Ngrok account](https://dashboard.ngrok.com/signup) (optional)
-   A free Twilio account (If you [register here](https://www.twilio.com/referral/OhKZOM), you'll receive $10 in Twilio credit when you upgrade to a paid account!)





You can find [the source code for this tutorial on GitHub](https://github.com/Swimburger/NgrokAspNet). Use the source code if you run into any issues, or submit an issue on this GitHub repo if you run into problems.




## Create an ASP.NET Core web project {#create-an-aspnet-core-web-project}




Open your preferred shell, and use the commands below to create a new folder named *NgrokAspNet*, and navigate to it:




<pre style="color:#000000;background:#ffffff;">mkdir NgrokAspNet&#10;<span style="color:#7f0055; font-weight:bold; ">cd</span> NgrokAspNet&#10;</pre>

Use the .NET CLI to create a new empty web project:

<pre style="color:#000000;background:#ffffff;">dotnet new web&#10;</pre>




Your new project contains one C# file, named *Program.cs*:




<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; font-weight:bold; ">var</span> builder = WebApplication.CreateBuilder(args);&#10;<span style="color:#7f0055; font-weight:bold; ">var</span> app = builder.Build();&#10;&#10;app.MapGet(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">/</span><span style="color:#2a00ff; ">"</span>, () =&gt; <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Hello World!</span><span style="color:#2a00ff; ">"</span>);&#10;&#10;app.Run();&#10;</pre>

The program creates a new web application with a single endpoint responding with "Hello World". Head back to your shell and start the project using the .NET CLI:

<pre style="color:#000000;background:#ffffff;">dotnet run&#10;</pre>

The output should look like this:

<pre style="color:#000000;background:#ffffff;">Building...&#10;info: Microsoft.Hosting.Lifetime[14]&#10;      Now listening on: <span style="color:#3f3fbf; ">https://localhost:7121</span>&#10;info: Microsoft.Hosting.Lifetime[14]&#10;      Now listening on: <span style="color:#3f3fbf; ">http://localhost:5033</span>&#10;info: Microsoft.Hosting.Lifetime[0]&#10;      Application started. Press Ctrl+C to shut down.&#10;info: Microsoft.Hosting.Lifetime[0]&#10;      Hosting environment: Development&#10;info: Microsoft.Hosting.Lifetime[0]&#10;      Content root path: /Users/nswimberghe/NgrokAspNet/&#10;</pre>




<strong>Take note of the two </strong><strong><em>localhost</em></strong><strong> URLs</strong> chosen for you, when you generated the web project.<br>Pick one of the URLs and open it in a web browser. You should see "Hello World!" displayed in your browser.




<p class="panel panel--warning">Leave the .NET project running and open a new shell to run the following commands!</p>



## Use ngrok to tunnel your local web server to the internet {#use-ngrok-to-tunnel-your-local-web-server-to-the-internet}



<p>You can run the ngrok CLI tool on your machine to tunnel the local URL to a public URL that looks similar to <em>https://66a605a7ced5.ngrok.io</em>, with a different subdomain. ​​Every time you start a new tunnel using ngrok, the subdomain is different.</p>

In your new shell, run the following command:

<pre style="color:#000000;background:#ffffff;">ngrok http <span style="color:#2a00ff; ">[</span><span style="color:#2a00ff; ">YOUR_HTTP_SERVER_URL</span><span style="color:#2a00ff; ">]</span>&#10;</pre>



<p>Replace <strong>[YOUR_HTTP_SERVER_URL]</strong> with the web server URL starting with <strong><em>http://localhost</em></strong>.</p>

This will start a new tunnel to a new public URL that you can find in the displayed output:

<p><img class="richtext-image left" src="https://twilio-cms-prod.s3.amazonaws.com/images/SI5f9KfjeLpf6BwG-rpTrHwE4nIMsRW-HqwyeyNWm4iCRh.width-500.png" alt="Ngrok output showing the two public URLs forwarding the local web server URLs" width="500" height="292"></p>

Switch back to the web browser and navigate to one of the **Forwarding URLs** listed in your shell. Some browsers may warn you that this is a deceptive site, which you can disregard in this case. The browser should once again return "Hello World", but this time via the public URL. This means you can share this URL with anyone, and they will also be able to communicate with your local web server. This also means webhooks can reach your local server.

<p>You can also tunnel HTTPS URLs, but you need to sign up for <a href="https://ngrok.com/">an ngrok account</a> (free) and <a href="https://ngrok.com/docs#getting-started-authtoken">authenticate your ngrok CLI tool</a>. Once you have done that, you can also run the <code>ngrok http</code> command with the URL starting with <em>https://localhost</em> instead.</p>



<p>In addition to the forwarding URLs, there's also a Web Interface URL displayed. This is where you can access ngrok's local dashboard and API. Switch back to your browser and <strong>navigate to </strong><strong><em>http://localhost:4040</em></strong>. Here you will find the forwarding URLs once again, and also a log of all the HTTP requests coming through the tunnel.</p>




Stop the ngrok process by pressing ctrl + c and close this shell instance. Switch to your other shell and stop the .NET project by pressing **ctrl + c**.




## Start ngrok automatically during ASP.NET Core startup {#start-ngrok-automatically-during-aspnet-core-startup}

You were able to publicly serve your web application by running your ASP.NET project and then running ngrok in a separate shell. This workflow can be optimized by integrating ngrok into the startup process of your ASP.NET project.


To start the ngrok tunnel programmatically, you'll need to run the ngrok CLI command from code. You could use the `Process` .NET APIs, but there's an open-source library that makes interacting with CLI tools and processes easier: [CliWrap](https://github.com/Tyrrrz/CliWrap).


Add the [CliWrap NuGet package](https://www.nuget.org/packages/CliWrap) using the .NET CLI:

<pre style="color:#000000;background:#ffffff;">dotnet add package CliWrap&#10;</pre>



<p class="panel panel--info">The CliWrap NuGet package is at version 3.4.0 at the time of writing this.</p>




Create a new C# file in the <em>NgrokAspNet </em>project directory, named <em>TunnelService.cs</em>, and add the following code:




<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; font-weight:bold; ">using</span> System.Text.Json.Nodes;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> CliWrap;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> Microsoft.AspNetCore.Hosting.Server;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> Microsoft.AspNetCore.Hosting.Server.Features;&#10;&#10;<span style="color:#7f0055; font-weight:bold; ">namespace</span> NgrokAspNet;&#10;&#10;<span style="color:#7f0055; font-weight:bold; ">public</span> <span style="color:#7f0055; font-weight:bold; ">class</span> TunnelService : BackgroundService&#10;{&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> <span style="color:#7f0055; font-weight:bold; ">readonly</span> IServer server;&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> <span style="color:#7f0055; font-weight:bold; ">readonly</span> IHostApplicationLifetime hostApplicationLifetime;&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> <span style="color:#7f0055; font-weight:bold; ">readonly</span> IConfiguration config;&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> <span style="color:#7f0055; font-weight:bold; ">readonly</span> ILogger&lt;TunnelService&gt; logger;&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">public</span> TunnelService(&#10;        IServer server,&#10;        IHostApplicationLifetime hostApplicationLifetime,&#10;        IConfiguration config,&#10;        ILogger&lt;TunnelService&gt; logger&#10;    )&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.server = server;&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.hostApplicationLifetime = hostApplicationLifetime;&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.config = config;&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.logger = logger;&#10;    }&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">protected</span> <span style="color:#7f0055; font-weight:bold; ">override</span> async Task ExecuteAsync(CancellationToken stoppingToken)&#10;    {&#10;        await WaitForApplicationStarted();&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> urls = server.Features.Get&lt;IServerAddressesFeature&gt;()!.Addresses;&#10;        <span style="color:#3f7f59; ">// Use https:// if you authenticated ngrok, otherwise, you can only use http://</span>&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> localUrl = urls.Single(u =&gt; u.StartsWith(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">http://</span><span style="color:#2a00ff; ">"</span>));&#10;&#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Starting ngrok tunnel for {LocalUrl}</span><span style="color:#2a00ff; ">"</span>, localUrl);&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> ngrokTask = StartNgrokTunnel(localUrl, stoppingToken);&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> publicUrl = await GetNgrokPublicUrl();&#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Public ngrok URL: {NgrokPublicUrl}</span><span style="color:#2a00ff; ">"</span>, publicUrl);&#10;&#10;        await ngrokTask;&#10;        &#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Ngrok tunnel stopped</span><span style="color:#2a00ff; ">"</span>);&#10;    }&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> Task WaitForApplicationStarted()&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> completionSource = <span style="color:#7f0055; font-weight:bold; ">new</span> TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);&#10;        hostApplicationLifetime.ApplicationStarted.Register(() =&gt; completionSource.TrySetResult());&#10;        <span style="color:#7f0055; font-weight:bold; ">return</span> completionSource.Task;&#10;    }&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> CommandTask&lt;CommandResult&gt; StartNgrokTunnel(<span style="color:#7f0055; font-weight:bold; ">string</span> localUrl, CancellationToken stoppingToken)&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> ngrokTask = Cli.Wrap(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">ngrok</span><span style="color:#2a00ff; ">"</span>)&#10;            .WithArguments(args =&gt; args&#10;                .Add(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">http</span><span style="color:#2a00ff; ">"</span>)&#10;                .Add(localUrl)&#10;                .Add(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">--log</span><span style="color:#2a00ff; ">"</span>)&#10;                .Add(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">stdout</span><span style="color:#2a00ff; ">"</span>))&#10;            .WithStandardOutputPipe(PipeTarget.ToDelegate(s =&gt; logger.LogDebug(s)))&#10;            .WithStandardErrorPipe(PipeTarget.ToDelegate(s =&gt; logger.LogError(s)))&#10;            .ExecuteAsync(stoppingToken);&#10;        <span style="color:#7f0055; font-weight:bold; ">return</span> ngrokTask;&#10;    }&#10;&#10;    <span style="color:#7f0055; font-weight:bold; ">private</span> async Task&lt;<span style="color:#7f0055; font-weight:bold; ">string</span>&gt; GetNgrokPublicUrl()&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">using</span> <span style="color:#7f0055; font-weight:bold; ">var</span> httpClient = <span style="color:#7f0055; font-weight:bold; ">new</span> HttpClient();&#10;        <span style="color:#7f0055; font-weight:bold; ">for</span> (<span style="color:#7f0055; font-weight:bold; ">var</span> ngrokRetryCount = 0; ngrokRetryCount &lt; 10; ngrokRetryCount++)&#10;        {&#10;            logger.LogDebug(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Get ngrok tunnels attempt: {RetryCount}</span><span style="color:#2a00ff; ">"</span>, ngrokRetryCount + 1);&#10;&#10;            <span style="color:#7f0055; font-weight:bold; ">try</span>&#10;            {&#10;                <span style="color:#7f0055; font-weight:bold; ">var</span> json = await httpClient.GetFromJsonAsync&lt;JsonNode&gt;(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">http://127.0.0.1:4040/api/tunnels</span><span style="color:#2a00ff; ">"</span>);&#10;                <span style="color:#7f0055; font-weight:bold; ">var</span> publicUrl = json[<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">tunnels</span><span style="color:#2a00ff; ">"</span>].AsArray()&#10;                    .Select(e =&gt; e[<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">public_url</span><span style="color:#2a00ff; ">"</span>].GetValue&lt;<span style="color:#7f0055; font-weight:bold; ">string</span>&gt;())&#10;                    .SingleOrDefault(u =&gt; u.StartsWith(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">https://</span><span style="color:#2a00ff; ">"</span>));&#10;                <span style="color:#7f0055; font-weight:bold; ">if</span> (!<span style="color:#7f0055; font-weight:bold; ">string</span>.IsNullOrEmpty(publicUrl)) <span style="color:#7f0055; font-weight:bold; ">return</span> publicUrl;&#10;            }&#10;            <span style="color:#7f0055; font-weight:bold; ">catch</span>&#10;            {&#10;                <span style="color:#3f7f59; ">// ignored</span>&#10;            }&#10;&#10;            await Task.Delay(200);&#10;        }&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">throw</span> <span style="color:#7f0055; font-weight:bold; ">new</span> Exception(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Ngrok dashboard did not start in 10 tries</span><span style="color:#2a00ff; ">"</span>);&#10;    }&#10;}&#10;</pre>

The `TunnelService` class will be responsible for starting a tunnel using the ngrok CLI, and later on it will also configure Twilio webhooks.

This is a lot of code, so let's dissect it piece by piece.

<pre style="color:#000000;background:#ffffff;">    <span style="color:#7f0055; font-weight:bold; ">public</span> TunnelService(&#10;        IServer server,&#10;        IHostApplicationLifetime hostApplicationLifetime,&#10;        IConfiguration config,&#10;        ILogger&lt;TunnelService&gt; logger&#10;    )&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.server = server;&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.hostApplicationLifetime = hostApplicationLifetime;&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.config = config;&#10;        <span style="color:#7f0055; font-weight:bold; ">this</span>.logger = logger;&#10;    }&#10;</pre>

The constructor accepts multiple parameters that will be provided by the dependency injection container built into ASP.NET Core. All the parameters are stored in private fields, so they are accessible throughout the class.


-   The `server` parameter contains information about the web server currently being started. Once the web server is started, you can retrieve the local URLs from the `server` field.
-   The `hostApplicationLifetime` parameter lets you hook into the different lifecycle events (started/stopping/stopped).<br>The `config` parameter will contain all the configuration passed into the .NET application through command-line arguments, environment variables, JSON files, user-secrets, etc. The config isn't used right now, but it will be used in an upcoming section.
-   The `logger` parameter will be used to log any information relevant to running the tunnel.




<pre style="color:#000000;background:#ffffff;">    <span style="color:#7f0055; font-weight:bold; ">protected</span> <span style="color:#7f0055; font-weight:bold; ">override</span> async Task ExecuteAsync(CancellationToken stoppingToken)&#10;    {&#10;        await WaitForApplicationStarted();&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> urls = server.Features.Get&lt;IServerAddressesFeature&gt;()!.Addresses;&#10;        <span style="color:#3f7f59; ">// Use https:// if you authenticated ngrok, otherwise, you can only use http://</span>&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> localUrl = urls.Single(u =&gt; u.StartsWith(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">http://</span><span style="color:#2a00ff; ">"</span>));&#10;&#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Starting ngrok tunnel for {LocalUrl}</span><span style="color:#2a00ff; ">"</span>, localUrl);&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> ngrokTask = StartNgrokTunnel(localUrl, stoppingToken);&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> publicUrl = await GetNgrokPublicUrl();&#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Public ngrok URL: {NgrokPublicUrl}</span><span style="color:#2a00ff; ">"</span>, publicUrl);&#10;&#10;        await ngrokTask;&#10;        &#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Ngrok tunnel stopped</span><span style="color:#2a00ff; ">"</span>);&#10;    }&#10;</pre>




`TunnelService` inherits from the abstract class `BackgroundService` which is why you need to implement the abstract method `ExecuteAsync`. `ExecuteAsync` is the main method of this class and will be invoked as the web application is starting. `ExecuteAsync` will wait for the web application to have started using `WaitForApplicationStarted`, and then grab the local URLs. A single URL will be taken from the local URLs. If you authenticated ngrok earlier, you can use the HTTPS URL instead of the HTTP URL by replacing `"http://"` with `"https://"`.





Next, the ngrok tunnel will be started, then the public ngrok URL will be retrieved, and finally the <code>Task</code> for running the ngrok CLI is awaited. When the web application stops, the ngrok process will also be stopped, which will complete the <code>ngrokTask</code>. 




<pre style="color:#000000;background:#ffffff;">    <span style="color:#7f0055; font-weight:bold; ">private</span> Task WaitForApplicationStarted()&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> completionSource = <span style="color:#7f0055; font-weight:bold; ">new</span> TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);&#10;        hostApplicationLifetime.ApplicationStarted.Register(() =&gt; completionSource.TrySetResult());&#10;        <span style="color:#7f0055; font-weight:bold; ">return</span> completionSource.Task;&#10;    }&#10;</pre>




`WaitForApplicationStarted` will create an awaitable `Task` that will be completed when the `ApplicationStarted` event is triggered. Oddly, the lifecycle events on `IHostApplicationLifetime` are not using delegates or [C# events](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/), but instead they are `CancellationToken`'s.


You can pass in a lambda or delegate to the `CancellationToken.Register` method which will be invoked when the `CancellationToken` is canceled. In case of the cancellation token stored in the `IHostApplicationLifetime.ApplicationStarted` property, when the token is canceled, this means the application has started. How (un)intuitive, am I right?


To make this more intuitive to use, you can create a <code>TaskCompletionSource</code> and set its result in the <code>hostApplicationLifetime.ApplicationStarted.Register</code> callback. This will set the <code>Task</code> as completed, which in this case will be when the application has started. 


If all of this is a little confusing, the important thing to take away is that `await WaitForApplicationStarted()` will wait for the web application to have started.

<pre style="color:#000000;background:#ffffff;">    <span style="color:#7f0055; font-weight:bold; ">private</span> CommandTask&lt;CommandResult&gt; StartNgrokTunnel(<span style="color:#7f0055; font-weight:bold; ">string</span> localUrl, CancellationToken stoppingToken)&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> ngrokTask = Cli.Wrap(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">ngrok</span><span style="color:#2a00ff; ">"</span>)&#10;            .WithArguments(args =&gt; args&#10;                .Add(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">http</span><span style="color:#2a00ff; ">"</span>)&#10;                .Add(localUrl)&#10;                .Add(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">--log</span><span style="color:#2a00ff; ">"</span>)&#10;                .Add(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">stdout</span><span style="color:#2a00ff; ">"</span>))&#10;            .WithStandardOutputPipe(PipeTarget.ToDelegate(s =&gt; logger.LogDebug(s)))&#10;            .WithStandardErrorPipe(PipeTarget.ToDelegate(s =&gt; logger.LogError(s)))&#10;            .ExecuteAsync(stoppingToken);&#10;        <span style="color:#7f0055; font-weight:bold; ">return</span> ngrokTask;&#10;    }&#10;</pre>

`StartNgrokTunnel` will use the CliWrap library to run the ngrok CLI. The resulting command will look like this:

<pre style="color:#000000;background:#ffffff;">ngrok http <span style="color:#2a00ff; ">[</span><span style="color:#2a00ff; ">YOUR_LOCAL_SERVER_URL</span><span style="color:#2a00ff; ">]</span> --log stdout&#10;</pre>




This command will start the ngrok tunnel like before, but with the addition of the `--log stdout` argument. This log argument instructs ngrok to log to standard output which can then be captured through `WithStandardOutputPipe`.  The standard output and error output will be piped to the `logger`.





A critical detail is that the `stoppingToken` is passed to `ExecuteAsync`. The `stoppingToken` will be canceled when the application is being stopped. You can use this token to gracefully handle when the application is about to be shutdown. By passing the `stoppingToken` to `ExecuteAsync`, the ngrok process will also be stopped when the application is stopped. Thus, you won't have any ngrok child processes lingering around.




<pre style="color:#000000;background:#ffffff;">    <span style="color:#7f0055; font-weight:bold; ">private</span> async Task&lt;<span style="color:#7f0055; font-weight:bold; ">string</span>&gt; GetNgrokPublicUrl()&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">using</span> <span style="color:#7f0055; font-weight:bold; ">var</span> httpClient = <span style="color:#7f0055; font-weight:bold; ">new</span> HttpClient();&#10;        <span style="color:#7f0055; font-weight:bold; ">for</span> (<span style="color:#7f0055; font-weight:bold; ">var</span> ngrokRetryCount = 0; ngrokRetryCount &lt; 10; ngrokRetryCount++)&#10;        {&#10;            logger.LogDebug(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Get ngrok tunnels attempt: {RetryCount}</span><span style="color:#2a00ff; ">"</span>, ngrokRetryCount + 1);&#10;&#10;            <span style="color:#7f0055; font-weight:bold; ">try</span>&#10;            {&#10;                <span style="color:#7f0055; font-weight:bold; ">var</span> json = await httpClient.GetFromJsonAsync&lt;JsonNode&gt;(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">http://127.0.0.1:4040/api/tunnels</span><span style="color:#2a00ff; ">"</span>);&#10;                <span style="color:#7f0055; font-weight:bold; ">var</span> publicUrl = json[<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">tunnels</span><span style="color:#2a00ff; ">"</span>].AsArray()&#10;                    .Select(e =&gt; e[<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">public_url</span><span style="color:#2a00ff; ">"</span>].GetValue&lt;<span style="color:#7f0055; font-weight:bold; ">string</span>&gt;())&#10;                    .SingleOrDefault(u =&gt; u.StartsWith(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">https://</span><span style="color:#2a00ff; ">"</span>));&#10;                <span style="color:#7f0055; font-weight:bold; ">if</span> (!<span style="color:#7f0055; font-weight:bold; ">string</span>.IsNullOrEmpty(publicUrl)) <span style="color:#7f0055; font-weight:bold; ">return</span> publicUrl;&#10;            }&#10;            <span style="color:#7f0055; font-weight:bold; ">catch</span>&#10;            {&#10;                <span style="color:#3f7f59; ">// ignored</span>&#10;            }&#10;&#10;            await Task.Delay(200);&#10;        }&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">throw</span> <span style="color:#7f0055; font-weight:bold; ">new</span> Exception(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Ngrok dashboard did not start in 10 tries</span><span style="color:#2a00ff; ">"</span>);&#10;    }&#10;</pre>



<p>The <code>GetNgrokPublicUrl</code> will fetch the public HTTPS URL and return it. You can get the public tunnel URLs by requesting it from the local ngrok API at <em>http://127.0.0.1:4040/api/tunnels</em>. </p>

Unfortunately, when the ngrok CLI is started, that doesn't mean the tunnel is ready yet. That's why this code is surrounded in a loop that will try to get the public URL up to 10 times, every 200 milliseconds. Feel free to change the 200ms delay and the `retryCount` to whatever suits your needs.


The `TunnelService` class is complete, but you still need to configure the web application to run it in the background. Update *Program.cs*, based on the highlighted lines below:




<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; font-weight:bold; ">var</span> builder = WebApplication.CreateBuilder(args);&#10;<span style="color:#7f0055; font-weight:bold; ">if</span> (builder.Environment.IsDevelopment()) &#10;    builder.Services.AddHostedService&lt;NgrokAspNet.TunnelService&gt;();&#10;<span style="color:#7f0055; font-weight:bold; ">var</span> app = builder.Build();&#10;&#10;app.MapGet(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">/</span><span style="color:#2a00ff; ">"</span>, () =&gt; <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Hello World!</span><span style="color:#2a00ff; ">"</span>);&#10;&#10;app.Run();&#10;</pre>




The <code>TunnelService</code> will be configured to run in the background, but only when the application is run in a development environment. After all, you only want to use the ngrok tunnel for local development. 




<p class="panel panel--warning">It doesn't make sense to run this in staging or production, and would probably cause trouble if it did run. Instead of only running this is in a development environment, you could also add a more explicit configuration element, but that's up to you!</p>

That's it! Run the application using the .NET CLI and watch the output:

<pre style="color:#000000;background:#ffffff;">dotnet run&#10;</pre>



<p>The public ngrok URL will be logged to the output like this: "Public ngrok URL: https://6797-72-66-29-154.ngrok.io". Grab the public ngrok URL and navigate to it in the browser. You will see, once again, "Hello World!".</p>



## Update Twilio Webhooks automatically with ngrok URLs {#update-twilio-webhooks-automatically-with-ngrok-urls}



### Get started with Twilio {#get-started-with-twilio}

If you haven't already, you'll need to set up the following with Twilio:


-   Go and [buy a new phone number from Twilio](https://support.twilio.com/hc/en-us/articles/223135247-How-to-Search-for-and-Buy-a-Twilio-Phone-Number-from-Console). The cost of the phone number will be applied to your free promotional credit.Make sure to take note of your new Twilio phone number. You'll need it later on!
-   If you are using a trial Twilio account, you can only send text messages to Verified Caller IDs. [Verify your phone number](https://support.twilio.com/hc/en-us/articles/223180048-Adding-a-Verified-Phone-Number-or-Caller-ID-with-Twilio) or the phone number you want to SMS if it isn't on the list of Verified Caller IDs.
-   Lastly, you'll need to find your Twilio Account SID and Auth Token. Navigate to your [Twilio account page](https://console.twilio.com/) and **take note of your Twilio Account SID and Auth Token** located at the bottom left of the page.<br><img class="richtext-image left" src="https://twilio-cms-prod.s3.amazonaws.com/images/IgBJX1YxVWLOE8zIxgg2mOxCuG0loJ_psxd4INAhsBLum2.width-500.png" alt="Account Info box holding 3 read-only fields: Account SID field, Auth Token field, and Twilio phone number field." width="500" height="275">




### Update Twilio Phone Number Webhooks {#update-twilio-phone-number-webhooks}

The [Twilio SDK for C# and .NET](https://www.twilio.com/docs/libraries/csharp-dotnet) will help you interact with Twilio's APIs and respond to webhooks. Add [the Twilio NuGet package](https://www.nuget.org/packages/Twilio) to your project:

<pre style="color:#000000;background:#ffffff;">dotnet add package twilio&#10;</pre>

<br>Go back to your code editor and open the *TunnelService.cs* file. Update the `using` statements at the top of the file, to include these three new Twilio references:

<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; font-weight:bold; ">using</span> System.Text.Json.Nodes;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> CliWrap;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> Microsoft.AspNetCore.Hosting.Server;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> Microsoft.AspNetCore.Hosting.Server.Features;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> Twilio.Clients;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> Twilio.Rest.Api.V2010.Account;&#10;<span style="color:#7f0055; font-weight:bold; ">using</span> Twilio.Types;&#10;</pre>

Update the `ExecuteAsync` method to invoke the asynchronous `ConfigureTwilioWebhook` method after logging the public ngrok URL:

<pre style="color:#000000;background:#ffffff;">    <span style="color:#7f0055; font-weight:bold; ">protected</span> <span style="color:#7f0055; font-weight:bold; ">override</span> async Task ExecuteAsync(CancellationToken stoppingToken)&#10;    {&#10;        await WaitForApplicationStarted();&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> urls = server.Features.Get&lt;IServerAddressesFeature&gt;()!.Addresses;&#10;        <span style="color:#3f7f59; ">// Use https:// if you authenticated ngrok, otherwise, you can only use http://</span>&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> localUrl = urls.Single(u =&gt; u.StartsWith(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">http://</span><span style="color:#2a00ff; ">"</span>));&#10;&#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Starting ngrok tunnel for {LocalUrl}</span><span style="color:#2a00ff; ">"</span>, localUrl);&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> ngrokTask = StartNgrokTunnel(localUrl, stoppingToken);&#10;&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> publicUrl = await GetNgrokPublicUrl();&#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Public ngrok URL: {NgrokPublicUrl}</span><span style="color:#2a00ff; ">"</span>, publicUrl);&#10;&#10;        await ConfigureTwilioWebhook(publicUrl);&#10;        &#10;        await ngrokTask;&#10;        &#10;        logger.LogInformation(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Ngrok tunnel stopped</span><span style="color:#2a00ff; ">"</span>);&#10;    }&#10;</pre>

Add the asynchronous `ConfigureTwilioWebhook` method after the `GetNgrokPublicUrl` method:

<pre style="color:#000000;background:#ffffff;">    <span style="color:#7f0055; font-weight:bold; ">private</span> async Task ConfigureTwilioWebhook(<span style="color:#7f0055; font-weight:bold; ">string</span> publicUrl)&#10;    {&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> twilioClient = <span style="color:#7f0055; font-weight:bold; ">new</span> TwilioRestClient(config[<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">TwilioAccountSid</span><span style="color:#2a00ff; ">"</span>], config[<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">TwilioAuthToken</span><span style="color:#2a00ff; ">"</span>]);&#10;        <span style="color:#7f0055; font-weight:bold; ">var</span> phoneNumber = (await IncomingPhoneNumberResource.ReadAsync(&#10;            phoneNumber: <span style="color:#7f0055; font-weight:bold; ">new</span> PhoneNumber(config[<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">TwilioPhoneNumber</span><span style="color:#2a00ff; ">"</span>]),&#10;            limit: 1,&#10;            client: twilioClient&#10;        )).Single();&#10;        phoneNumber = await IncomingPhoneNumberResource.UpdateAsync(&#10;            phoneNumber.Sid,&#10;            voiceUrl: <span style="color:#7f0055; font-weight:bold; ">new</span> Uri($<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">{publicUrl}/voice</span><span style="color:#2a00ff; ">"</span>), voiceMethod: Twilio.Http.HttpMethod.Post,&#10;            smsUrl: <span style="color:#7f0055; font-weight:bold; ">new</span> Uri($<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">{publicUrl}/message</span><span style="color:#2a00ff; ">"</span>), smsMethod: Twilio.Http.HttpMethod.Post,&#10;            client: twilioClient&#10;        );&#10;        logger.LogInformation(&#10;            <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Twilio Phone Number {TwilioPhoneNumber} Voice URL updated to {TwilioVoiceUrl}</span><span style="color:#2a00ff; ">"</span>,&#10;            phoneNumber.PhoneNumber,&#10;            phoneNumber.VoiceUrl&#10;        );&#10;        logger.LogInformation(&#10;            <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Twilio Phone Number {TwilioPhoneNumber} Message URL updated to {TwilioMessageUrl}</span><span style="color:#2a00ff; ">"</span>,&#10;            phoneNumber.PhoneNumber,&#10;            phoneNumber.SmsUrl&#10;        );&#10;    }&#10;</pre>




The <code>​​ConfigureTwilioWebhook</code> method receives the public ngrok URL as a parameter. The <strong>Account SID</strong> and <strong>Auth Token</strong> are retrieved from the <code>config</code> field and passed into the constructor of <code>TwilioRestClient</code>. 




<p class="panel panel--warning">You can <a href="https://www.twilio.com/blog/better-twilio-authentication-csharp-twilio-api-keys">use API keys to authenticate instead of using the Account SID and the Auth Token</a>. API keys have fewer permissions and can be revoked more easily, which makes them a safer option.</p>




The Twilio phone number details are requested using <code>TwilioRestClient</code>, and then the phone number details are used to update the voice webhook URL and the SMS webhook URL. The voice and SMS webhook URLs will be set to the public tunnel URL with <code>/voice</code> and <code>/message</code> appended to it, respectively<em>.</em> 





The project now depends on the `TwilioAccountSid`, `TwilioAuthToken`, and `TwilioPhoneNumber` configuration element, but they haven't been configured yet. You can use .NET user secrets to configure these types of sensitive configuration.


Initialize user secrets for your project using the .NET CLI:

<pre style="color:#000000;background:#ffffff;">dotnet user-secrets init&#10;</pre>

Run the following command to configure the secrets:

<pre style="color:#000000;background:#ffffff;">dotnet user-secrets <span style="color:#7f0055; font-weight:bold; ">set</span> TwilioAccountSid <span style="color:#2a00ff; ">[</span><span style="color:#2a00ff; ">YOUR ACCOUNT SID</span><span style="color:#2a00ff; ">]</span>&#10;dotnet user-secrets <span style="color:#7f0055; font-weight:bold; ">set</span> TwilioAuthToken <span style="color:#2a00ff; ">[</span><span style="color:#2a00ff; ">YOUR AUTH TOKEN</span><span style="color:#2a00ff; ">]</span>&#10;dotnet user-secrets <span style="color:#7f0055; font-weight:bold; ">set</span> TwilioPhoneNumber <span style="color:#2a00ff; ">[</span><span style="color:#2a00ff; ">YOUR TWILIO PHONE NUMBER</span><span style="color:#2a00ff; ">]</span>&#10;</pre>




Replace `[YOUR ACCOUNT SID]` with your Twilio **Account SID**, `[YOUR AUTH TOKEN]` with your Twilio **Auth Token**, and `[YOUR TWILIO PHONE NUMBER]` with your **Twilio Phone Number**.


Test out your work so far by running the application:

<pre style="color:#000000;background:#ffffff;">dotnet run&#10;</pre>



<p>You should see additional output that looks like this: "Twilio Phone Number +1234567890 Voice URL updated to https://5fb3-72-66-29-154.ngrok.io/voice" and "Twilio Phone Number +1234567890 Message URL updated to https://5fb3-72-66-29-154.ngrok.io/message"</p>



### Respond to Twilio webhooks {#respond-to-twilio-webhooks}




Once the webhook URLs are set, Twilio will send HTTP requests to your public URLs whenever a phone call or SMS goes to your Twilio phone number.<br>You need to accept these HTTP requests for `/voice` and `/message`*,* and then respond with [TwiML](https://www.twilio.com/docs/glossary/what-is-twilio-markup-language-twiml) instructions. Update *Program.cs* based on the highlighted lines in the code below:




<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; font-weight:bold; ">using</span> Twilio.TwiML;&#10;&#10;<span style="color:#7f0055; font-weight:bold; ">var</span> builder = WebApplication.CreateBuilder(args);&#10;<span style="color:#7f0055; font-weight:bold; ">if</span> (builder.Environment.IsDevelopment()) &#10;    builder.Services.AddHostedService&lt;NgrokAspNet.TunnelService&gt;();&#10;<span style="color:#7f0055; font-weight:bold; ">var</span> app = builder.Build();&#10;&#10;app.MapGet(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">/</span><span style="color:#2a00ff; ">"</span>, () =&gt; <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Hello World!</span><span style="color:#2a00ff; ">"</span>);&#10;app.MapPost(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">/voice</span><span style="color:#2a00ff; ">"</span>, () =&gt;&#10;{&#10;    <span style="color:#7f0055; font-weight:bold; ">var</span> response = <span style="color:#7f0055; font-weight:bold; ">new</span> VoiceResponse();&#10;    response.Say(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Hello World!</span><span style="color:#2a00ff; ">"</span>);&#10;    <span style="color:#7f0055; font-weight:bold; ">return</span> Results.Text(response.ToString(), <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">application/xml</span><span style="color:#2a00ff; ">"</span>);&#10;});&#10;app.MapPost(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">/message</span><span style="color:#2a00ff; ">"</span>, () =&gt;&#10;{&#10;    <span style="color:#7f0055; font-weight:bold; ">var</span> response = <span style="color:#7f0055; font-weight:bold; ">new</span> MessagingResponse();&#10;    response.Message(<span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">Hello World!</span><span style="color:#2a00ff; ">"</span>);&#10;    <span style="color:#7f0055; font-weight:bold; ">return</span> Results.Text(response.ToString(), <span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">application/xml</span><span style="color:#2a00ff; ">"</span>);&#10;});&#10;&#10;app.Run();&#10;</pre>




When Twilio sends an HTTP POST request to `/voice`, the endpoint will respond with the following TwiML:




<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; ">&lt;?</span><span style="color:#7f0055; font-weight:bold; ">xml</span><span style="color:#7f0055; "> </span><span style="color:#7f0055; ">version</span><span style="color:#7f0055; ">=</span><span style="color:#2a00ff; ">"</span><span style="color:#7f0055; font-weight:bold; ">1.0</span><span style="color:#2a00ff; ">"</span><span style="color:#7f0055; "> </span><span style="color:#7f0055; ">encoding</span><span style="color:#7f0055; ">=</span><span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">utf-8</span><span style="color:#2a00ff; ">"</span><span style="color:#7f0055; ">?&gt;</span>&#10;<span style="color:#7f0055; ">&lt;</span><span style="color:#7f0055; ">Response</span><span style="color:#7f0055; ">&gt;</span>&#10;  <span style="color:#7f0055; ">&lt;</span><span style="color:#7f0055; ">Say</span><span style="color:#7f0055; ">&gt;</span>Hello World!<span style="color:#7f0055; ">&lt;/</span><span style="color:#7f0055; ">Say</span><span style="color:#7f0055; ">&gt;</span>&#10;<span style="color:#7f0055; ">&lt;/</span><span style="color:#7f0055; ">Response</span><span style="color:#7f0055; ">&gt;</span>&#10;</pre>

As a result, Twilio will transcribe "Hello World!" to audio and stream it to the caller.


When Twilio sends an HTTP POST request to `/message`, the endpoint will respond with the following TwiML:




<pre style="color:#000000;background:#ffffff;"><span style="color:#7f0055; ">&lt;?</span><span style="color:#7f0055; font-weight:bold; ">xml</span><span style="color:#7f0055; "> </span><span style="color:#7f0055; ">version</span><span style="color:#7f0055; ">=</span><span style="color:#2a00ff; ">"</span><span style="color:#7f0055; font-weight:bold; ">1.0</span><span style="color:#2a00ff; ">"</span><span style="color:#7f0055; "> </span><span style="color:#7f0055; ">encoding</span><span style="color:#7f0055; ">=</span><span style="color:#2a00ff; ">"</span><span style="color:#2a00ff; ">utf-8</span><span style="color:#2a00ff; ">"</span><span style="color:#7f0055; ">?&gt;</span>&#10;<span style="color:#7f0055; ">&lt;</span><span style="color:#7f0055; ">Response</span><span style="color:#7f0055; ">&gt;</span>&#10;  <span style="color:#7f0055; ">&lt;</span><span style="color:#7f0055; ">Message</span><span style="color:#7f0055; ">&gt;</span>Hello World!<span style="color:#7f0055; ">&lt;/</span><span style="color:#7f0055; ">Message</span><span style="color:#7f0055; ">&gt;</span>&#10;<span style="color:#7f0055; ">&lt;/</span><span style="color:#7f0055; ">Response</span><span style="color:#7f0055; ">&gt;</span>&#10;</pre>

As a result, Twilio will respond with a text message saying "Hello World!".

### Testing the Twilio webhooks {#testing-the-twilio-webhooks}




If everything went well, you are now able to develop and test webhooks by running a single command `dotnet run`. Start the application using the .NET CLI:




<pre style="color:#000000;background:#ffffff;">dotnet run&#10;</pre>

Wait for the webhook URLs to be updated, and then call and/or text your Twilio Phone Number.<br>If you call, you should hear "Hello World!", and if you text, you should receive a text message saying "Hello World!".

## How to integrate ngrok into ASP.NET and automatically update your webhooks {#how-to-integrate-ngrok-into-aspnet-and-automatically-update-your-webhooks}

In this tutorial, you learned how to streamline your webhook development process by integrating ngrok into your ASP.NET Core startup and automatically updating your webhooks, using these steps:


1.  Get your local ASP.NET URLs
2.  Use a `BackgroundService` to run the ngrok tunnel
3.  Fetch the ngrok forwarding URL from ngrok's local API
4.  Update your webhooks URLs using the ngrok forwarding URL





Twilio has a lot of other products you can integrate into your applications. Check out [this tutorial on how to make phone calls from Blazor WebAssembly with Twilio Voice and Twilio Client](https://www.twilio.com/blog/making-phone-calls-from-blazor-webassembly-with-twilio-voice).




## Additional resources {#additional-resources}

Check out the following resources for more information on the topics and tools presented in this tutorial:


<a href="https://www.twilio.com/docs/voice/twiml">TwiML for Programmable Voice</a> – Learn more about TwiML and how you can use TwiML to handle phone calls. 





<a href="https://www.twilio.com/docs/messaging/twiml">TwiML for Programmable SMS</a> – Learn more about TwiML and how you can use TwiML to respond to text messages. 


[Source Code for this tutorial on GitHub](https://github.com/Swimburger/NgrokAspNet) - Use this source code if you run into any issues, or submit an issue on this GitHub repo if you run into problems.


<em>Niels Swimberghe is a Belgian American software engineer and technical content creator at Twilio. Get in touch with Niels on </em><a href="https://twitter.com/RealSwimburger"><em>Twitter @RealSwimburger</em></a><em> and follow Niels’ personal blog on .NET, Azure, and web development at </em><a href="https://swimburger.net/"><em>swimburger.net</em></a><em>.</em>
