メニュー

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

WindowsとVisual Studio環境でWebhookのテストにngrokを使用する方法

Let's take a look at how a Windows developer building ASP.NET web apps can put ngrok to work. ngrok makes your local development machine securely accessible from the public Internet. Want to give your client a preview of the site you're working on? Do you need to debug a webhook for Twilio, GitHub, or another API provider? Use ngrok to get a public URL for your local web application.

The ngrok express lane: ngrok Extensions for Visual Studio

The quickest way to get started with ngrok and Visual Studio is to use an open source extension for Visual Studio that will start ngrok for any web applications that are part of the currently open solution. It will figure out the ports for you and fire up the necessary tunnels for your app(s).

ngrok Visual Studio Extension

Chose "Start ngrok Tunnel" from the Visual Studio "Tools" menu, ngrok will start, and you'll see your app's new public URL.

Visual Studioで実行されるngrok

ここでは、ngrokから次のようなURLが与えられています:https://a9f03915.ngrok.io Visual Studio内からアプリケーションが実行されていることを確認し、ブラウザーで上記のURLにアクセスしてみましょう。 ローカルの開発マシンからアプリケーションが読み込まれるはずです。 これで、他人に公開したり(Twilioコンソール内で行うような)Webhookの構成に使用したりするための、開発環境で実行されているアプリケーションにアクセスできるURLが入手できました。 コード中にブレークポイントを追加するなど、ローカルでのアプリケーションの実行時に行っていることをなんでも行うことができます。

You can leave ngrok running while you are working on your app. If you stop your app, ngrok can continue to run and will resume serving traffic to your app when you restart your app. If you do shut down ngrok, then you will be given a new URL when it restarts. This means if you've configured a webhook with your ngrok URL, you will need to update it each time you restart ngrok.

Windowsへのngrokのインストール

When you use the Visual Studio extension, it will automatically download and install ngrok for you. However, if you aren't using Visual Studio, you will need to install ngrok yourself.

Use the Chocolatey Package Manager

If you use the Chocolatey package manager (highly recommended), installation simply requires the following command from an elevated command prompt:

choco install ngrok.portable

これでngrokがPATHにインストールされ、任意のディレクトリーからこれを実行できるようになります。

手動でインストールする

ngrokの手動でのインストールは、追加でいくつかの手順が必要です。

  1. ngrokのZIPファイルをダウンロードします
  2. ngrok.exeファイルをを展開します
  3. ngrok.exeをお好みのフォルダーに配置します
  4. 上記フォルダーがパスの通った(PATH環境変数に記述のある)フォルダーであることを確認します

インストールを確認する

To test that ngrok is installed properly, open a new command window (command prompt or PowerShell) and run the following:

ngrok version

"ngrok version 2.x.x" という文字列が表示されるはずです。 「ngrokが見つかりません」などと表示される場合は、おそらくngrok.exeの含まれているフォルダーにパスが通っていない(PATH環境変数に記述されていない)ことが考えられます。 あるいは、新規でコマンド・ウィンドウを開いてみてください。

ngrokのインストールが完了したら、それをVisual Studioプロジェクトと一緒に使用できるようにしましょう。

Using ngrok manually with a Visual Studio hosted ASP.NET application

コマンドラインからのngrokの起動

ASP.NETアプリケーションをVisual Studioでホストする際、通常はIIS Expressを使用しますが、ご使用のVisual Studioのバージョンやアプリケーションの構成によっては、他のWebサーバー・ソフトウェアを使用することもできます。 セットアップの如何にかかわらず、開発中のアプリケーションに新しい公開トンネルを作成する際に実行すべき簡単なコマンドがひとつあります。

ngrok http -host-header="localhost:[port]" [port]

どのアプリケーションがどこのポートで実行されているかを確認するには、アプリケーションをVisual Studioから実行します。 新規のアプリケーションがWebブラウザーで起動すると、アドレスバーでURLが確認できます。

Visual Studio Webアプリケーションのポート

この例でのポート番号は58821ですが、Visual Studioは新規作成されたASP.NETプロジェクトごとにランダムなポート番号を割り当てることに気づかれるでしょう。 幸い、作業中の個別のプロジェクトについては、ポート名は一貫しています。

この例の場合、ngrokのコマンドは以下のようになります:

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

ngrokが起動し、開発中のアプリケーションの新しい公開URLが確認できるでしょう。

Visual Studioで実行されるngrok

ここでは、ngrokから次のようなURLが与えられています:https://a9f03915.ngrok.io Visual Studio内からアプリケーションが実行されていることを確認し、ブラウザーで上記のURLにアクセスしてみましょう。 ローカルの開発マシンからアプリケーションが読み込まれるはずです。 これで、他人に公開したり(Twilioコンソール内で行うような)Webhookの構成に使用したりするための、開発環境で実行されているアプリケーションにアクセスできるURLが入手できました。 コード中にブレークポイントを追加するなど、ローカルでのアプリケーションの実行時に行っていることをなんでも行うことができます。

You can leave ngrok running while you are working on your app. If you stop your app, ngrok can continue to run and will resume serving traffic to your app when you restart your app. If you do shut down ngrok, then you will be given a new URL when it restarts. This means if you've configured a webhook with your ngrok URL, you will need to update it each time you restart ngrok.

毎回同一のngrokドメインを使用する

ngrok offers paid plans that let you use custom domains such as "my-cool-app.ngrok.io". You can use the domain each time you start up ngrok, so there's no need to update webhook configurations. When you get a paid plan, you'll be given an authtoken that you need to install. You only need to run the command once:

ngrok authtoken [yourtoken]

Then, reserve your domain name and add the -subdomain argument to the command line:

ngrok http -host-header="localhost:58821" -subdomain my-cool-app 58821

Now, you can use https://my-cool-app.ngrok.io consistently to access your development environment.

If you are using the Visual Studio extension, specify the subdomain you would like it to use in the appSettings section of your web.config file like so:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ngrok-subdomain" value="my-cool-app"/>
    ... more appSettings omitted ...
  </appSettings>
  ... more config omitted ...
</configuration>

トラブルシューティング

Sometimes things can go wrong and when you can't seem to get your ngrok tunnel working, here are some things to try or consider:

  1. Is your app running? Not only does the tunnel need to be running, but your app also needs to be running in order to respond to requests.
  2. Did you start ngrok with the correct port number? Make sure the port that ngrok is forwarding traffic to matches the port that your application is listening on.
  3. Have you tried running ngrok manually? If you are using the Visual Studio extension and are having trouble, try running ngrok manually from the command line following the instructions in this guide. If you can get it working that way, please submit that feedback so we can improve the Visual Studio extension.
  4. Is your computer a company-managed machine? In some cases, computers managed by your company IT department may be locked down to prevent external tunneling software from working correctly. If this is the case, you could ask for an exception or you may need to use a public web host like Microsoft Azure to host your application publicly.

ngrokの上級テクニック

ngrokのホスト名を入手する

Perhaps you have some C# code that looks at the Request object to try to figure out the host name to use in an absolute URL. You might be doing something to insert a fully qualified URL into an email or maybe you're using the Twilio API to provision a phone number with a webhook URL to receive phone calls (that's a great idea, pat yourself on the back for thinking of that).

Regardless of the reason why, usually in ASP.NET when you want the host name, you use the Url.Host on the current request:

var myHostName = Request.Url.Host;

You probably combine that with Url.Port to make sure you're on the right port since your local development environment isn't on a default port:

var myHostNameWithPort = Request.Url.Host + ":" + Request.Url.Port;

So, if you open "http://localhost:1234/Home", you will get "localhost:1234". What if you are running your app through ngrok? Perhaps unexpectedly, the above code will still return "localhost:1234" even though you accessed the page with an ngrok URL like "https://foo123.ngrok.io/Home". This is because in order to get Visual Studio (and the IIS Express web server under the hood) to allow requests into your local environment, we had to instruct ngrok to rewrite the host header. Thankfully, there's an easy way around this because ngrok will pass us a X-Original-Host header that we can use.

Here's a C# function that will use the X-Original-Host if it is present, otherwise it will use the Url property like before:

public static string GetDomainAndPort(HttpRequestBase request)
{
    if (request.Headers["X-Original-Host"] != null)
    {
        // Assume default port for protocol (http=80, https=443)
        return request.Headers["X-Original-Host"];
    }

    // Leave off port if it's the default 80/443
    if (request.Url.Port == 80 || request.Url.Port == 443)
    {
        return request.Url.Host;
    }
    return request.Url.Host + ":" + request.Url.Port;
}

SSLステータスを取得する

If you're building a full URL, you probably want to know if you should prefix it with "http" or "https". ngrok supports both, so you could just default to https and be safe. If you want to know which protocol the user actually used, then you can check the X-Forwarded-Proto header:

public static string GetProtocol(HttpRequestBase request)
{
    if (request.Headers["X-Forwarded-Proto"] != null)
    {
        return request.Headers["X-Forwarded-Proto"];
    }

    return request.IsSecureConnection ? "https" : "http";
}

X-Forwarded-Proto is a fairly common header for front-end proxy servers, so the code is reusable whether you're running with ngrok in development or behind an AWS Elastic Load Balancer in production.

クライアントのIPアドレスを取得する

The other common header that is passed by proxies like ngrok is X-Forwarded-For. This header is used to provide the original IP address of the client making the HTTP request. If you only use the typcial UserHostAddress property of the current request object, then you will always get the IP address of the proxy server (in our case, one of ngrok's servers). Here's the correct way to detect the IP address of the client whether a proxy is in the mix or not:

public static string GetIpAddress(HttpRequestBase request)
{
    return request.Headers["X-Forwarded-For"]
           ?? request.UserHostAddress;
}

これら3つの関数を併用し、コントローラーから呼び出す方法についての例を示します。

public class TestController : Controller
{
    // GET: Test
    public ActionResult Index()
    {
        var html = "<html><body><pre>\n" +
           "Your Protocol: " + ProxyHelper.GetProtocol(Request) + "\n" +
           "Your Domain:Port: " + ProxyHelper.GetDomainAndPort(Request) + "\n" +
           "Your IP Address: " + ProxyHelper.GetIpAddress(Request) + "\n" +
           "</pre></body></html>";
        return Content(html);
    }
}

終わりに

ngrok is a fantastic tool for debugging webhooks and for web development in general. Hopefully, this guide has provided you with the skills you need to make ngrok work harmoniously with Visual Studio.

David Prothero Lizzie Siegle Paul Kamp Kat King Kevin Whinnery
Rate this page:

ヘルプが必要ですか?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.