ASP.NET Core – integrated with ngrok

Ngrok provides a public URLs for exposing your localweb server. When we develop ASP.NET Core application, sometimes we want to access from public but debug locally with Visual Studio.

In order to do that, we need to use some NAT or public DNS tools to map our ASP.NET Core application localhost url to a public one. Ngrok is a such tool and run standalone to expose a public url to map to our local host url.

ngrok is a command line exe tool and download it you can start to use it.

Example: Expose a web server on port 80 of your local machine to the internet:

ngrok http 80

When you start ngrok, it will display a UI in your terminal with the public URL of your tunnel and other status and metrics information about connections made over your tunnel.

So once you start your self-host ASP.NET Core application, your local host url may be: http://localhost:80 and when you open a url http://92832de0.ngrok.io which can be access public, the traffic will go to your localhost: http://localhost:80 So you can start debug public traffic with your local debug environment.

Furthermore, there is a way to integrated ngrok with your ASP.NET Core application, and you don’t need to do those manual steps, and just press F5 to lunch ngork and your application and binding them.

There is a nuget Ngrok.AspNetCore we can add to our project and integrate ngrok. Search Ngrok.AspNetCore in nuget package management:

Modify Main method in Program.cs file:

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();
    host.StartNgrokAsync();
    host.Run();
}

And modify ConfigureServices method in Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    ......
    services.AddNgrok();
}

Now run application and it will automatic start ngrok and binding to our application local url:

Leave a comment