Posted by Anuraj on Wednesday, February 28, 2018
This post is about consuming webhooks in ASP.NET Core. A WebHook is an HTTP callback: an HTTP POST that occurs when something happens; a simple event-notification via HTTP POST. From ASP.NET Core 2.1 preview onwards ASP.NET Core supports WebHooks. As usual, to use WebHooks, you need to install package for WebHook support. In this post I am consuming webhook from GitHub. So you need to install
Microsoft.AspNetCore.WebHooks.Receivers.GitHub. You can do it like this.
Once it is added, you can modify your startup -
ConfigureServices method to configure endpoint to receive notifications.
Next, you need handler to receive the notifications, you can create a controller action and decorate it with
This generic handler will be invoked when an event happened on your GitHub repository.
Now you have almost completed your application to receive webhooks. Next you need to configure GitHub to send WebHooks. To configure this, open your repository settings.
Select WebHooks menu, which will redirect to manage webhooks page, where you will be able to see existing webhooks and you can create new webhook.
You can click on the
Add WebHook button, which will show a form like this, where you need to provide the Payload URL, Content Type, Secret and events where this webhook need to trigger.
Since we are doing development, our application URL will be localhost, but this URL will not work in this case. Either you need to host it or you need some application like ngrok. ngrok will help you to expose your localhost URLs to fully qualified domain names which is accessible over internet. You need to download ngrok exe and execute it following command.
This command will start ngrok, which will provide a URL which will forward traffic to your aspnet core application running in 5000 port.
In the Add WebHook form you need to provide following values.
Next you need to open your appsettings file and configure the Secret key inside it like following.
Now you have completed the setup, run your application. And save the webhook by clicking on the Add WebHook button. If everything is ok, webhook will be created.
Next you can test this webhook by adding an issue. Also put a break point in the
GitHubHandler method. Then I created an issue in the repository.
Once it is created, your breakpoint will hit and the
data parameter has all the values, you can see the same in the VS Code debug console.
Happy Programming :)