How to Auto-Deploy Source Code to Web Server via Webhook

If you are using GitHub to manage your website source code, you can use webhooks to send GitHub events to external services. In this article, I will share how to deploy my website to IIS, as well as how to pull the source code and update the site automatically when there’s a push event triggered.

IIS Configuration in Windows 10

Open “Windows features” to activate IIS. By default, all of the “Application Development Features” are disabled. Select the required features.

Windows IIS feature

How to Use Visual C# to Handle HTTP Request

Create an empty ASP.NET web application in Visual Studio.

aspnet web app

Add an HTML file index.htm.

Add a generic handler Webhook.ashx.

generic handler

Publish the project.

asp publish

Select IIS > File System.

aspnet publish local

Launch IIS to add the website.

IIS deployment

Visit http://localhost/Webhook.ashx to check whether the URL can work in your web browser.

aspnet ashx

The next step is to run the git pull command in C#. We can refer to the sample code from CodeProject.

csharp command

I created a batch file for running relevant commands:

batchFile = Path.Combine(context.Server.MapPath("."), "github.bat");

The physical path of my project is d:\iis, so the github.bat is as follows:

cd d:\\iis
git pull

How to Expose the Local Web Server to the Internet

To use GitHub webhooks, we have to provide a valid URL. Ngrok is a good tool for exposing a local webserver to the internet.

ngrok http 80

ngrok iis

The webhook URL is now

How to Use GitHub Webhook to Trigger the Auto-Deployment

Once the URL is ready, we can create a new repository on GitHub.

github new repo

Add and push d:\iis to the remote repository.

Click Settings > Webhooks to add the payload URL:

github webhook

Clone the repository to a new folder or another PC. Do some changes to the index.html file and push the changes to GitHub.

The web server will receive an HTTP request instantly and execute the `git pull’ command.

Refresh the page to see the update.

Source Code