Model Binding with Episerver Forms Webhooks

Brian Oliver
Senior Advanced Developer

As we know, webhooks are POST requests containing JSON data in the body of the request. We also know that in version 1.0.0.9000 of Episerver Forms, the Content-Type header is set to application/x-www-form-urlencoded. Because of this mismatch, we are unable to use the default MVC model binding. It would be really nice to just define our action method as:

<p> CODE: https://gist.github.com/thec2group-blog/4334a8414112ca7fd4e77c54ab84e429.js</p>

But “fields” will be null every time.  Are we out of luck?  Must we wait and see if this issue gets resolved?  Did Pete the Cat cry?  Goodness, no.  He just kept walking along and singing his song  (I have kids that are into Pete the Cat, what can I say?).

The good news here is that the content type mismatch bug has been resolved in version 1.1.2.9000 of Episerver Forms, thanks to Episerver’s continuous release process. This means that if you are running the latest version of Episerver Forms, you can use the above signature for your action method, and “fields” will no longer be null every time.  Wahoo! We’re done, right?  Pack up and go on holiday?  I think not.

In my last post, I showed that some very relevant data for the submission is sent to your webhook in the form of HTTP headers. It would be nice to include this in our model. Plus, it would be great to add a little more structure to our incoming data. Roll up your sleeves, it’s about to get fun!

One last note of caution:  at some point, a property was added to the webhooks.  If you’re on the latest version, make sure the checkbox for “POST data in JSON format” is checked.

Edit Webhook

First off, let’s build a model for storing all this submission data. My model will contain two Dictionary<string, object> properties – one for the fields, and another for all those system column fields. Also, I recall there being three form-specific headers in the request, so I’ll make three string fields for those. The request body is going to deserialize as a list of key-value pairs, so I’ll create a single public method for adding a key-value pair. This method will take care of adding it to the proper dictionary:

<p> CODE: https://gist.github.com/thec2group-blog/9535b0e2180a33bf72f148b7d4cc4695.js</p>

Now that we have our model, we need a model binder. This will tell .NET how to translate the request into our model class:

<p> CODE: https://gist.github.com/thec2group-blog/1f7c143d4f738df6e6a2f831b44efcd5.js</p>

Now we can change the signature of our action method:

<p> CODE: https://gist.github.com/thec2group-blog/ffed4e5614a972165129271c83d4ae58.js</p>

Obviously, you wouldn’t go through all this just to turn around, serialize it, and write to the debug output window.  But this should give you some ideas for what’s possible with webhooks and Episerver Forms.

Happy webhooking!

Insights, Right to Your Inbox.