Automatically HTML Decode every string property posted to .NET WebAPI

A blanket solution to a common API problem


The .NET framework does a lot to help improve and speed up the development process. One of the areas it really shines in is API development. Using the WebAPI and, more recently, WebAPI 2 project types can save you a massive amount of effort when creating an API from scratch. Here’s a blanket solution for a common gotcha with API development in general.

If you’re developing an API for a product, chances are that you’ll need to do more than just receive data via GET requests. In order to send data back to the server, or to retrieve data based on a variable, you’re going to be issuing POST or PUT requests to the server. When you do that, a commonly overlooked condition is the fact that those POST operations need to send strings as HTML encoded values in order to be transmitted successfully. If you’re not decoding those strings on the other end, you end up with special characters like the ampersand (&) being stored and displayed in its encoded form &amp instead.

This problem happens to everyone who builds an API and an AJAX client to interact with it. It’s not a difficult problem to solve, but we got to wondering how you might solve this in a single shot for .NET projects. You could decode every string property that comes into your API like so:

but that’s tedious and you still need to remember to do it on new API actions. Wouldn’t it be nice if you could capture every posted string and automatically HTML Decode it before it hits your API action? After all, there is no harm in decoding a string that has no encoded elements. We thought it would be a good strategy for our model heavy API which deals with a lot of strings so we came up with an Action Filter Attribute to do just that.

It intercepts any POST or PUT request, checks to see if the payload has data properties, then iterates over the properties looking for properties of type string. If a string property is found, it’s decoded.

Usage is simple, you decorate the entire controller, or the specific action with [HttpStringDecodeFilter] and you’re good to go. Before your controller action even gets the posted model, any string will already be decoded.

Head over to the GitHub repo for more documentation and examples, and to download the code.

Photo Credit: 
Join us:






Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Ask a Question