URL Decode

I had a sort-of simple bug to fix at work recently where for a given record, some of the time, a field was percent encoded. Specifically, the spaces were “%20” (sometimes, but not always). This was fine for my team, but for another team that also used that data, this was a problem.

One of the things that made this less-than-simple to fix was that my team didn’t generate this data. We received it from another team. I worked with this team to figure out how to resolve this so that going forward, my team was only storing un-encoded URLs. This seemed to work for about eighty percent of cases, but QA found a few spots I’d missed.

What to do?

UrlDecode to the rescue!
https://docs.microsoft.com/en-us/dotnet/api/system.web.httputility.urldecode?view=netframework-4.7.2

I mocked up a totally useless scenario here: https://dotnetfiddle.net/Xj8WVK# (code below in case the link doesn’t load)

using System;
using System.Web;

public class Program
{
	public static void Main()
	{
		var encodedUrl = "http://sometestdomain.com/a%20subdirectory/test%20green%20cheese%20purple%20in%20the%20moon.xlsx";
		var unEncodedUrl = "http://sometestdomain.com/a subdirectory/apples peaches pumpkin pie.xlsx";
		var decodeEncodedUrl = HttpUtility.UrlDecode(encodedUrl);
		var decodeUnencodedUrl = HttpUtility.UrlDecode(unEncodedUrl);
		Console.WriteLine(decodeEncodedUrl);
		Console.WriteLine(decodeUnencodedUrl);
	}
}

The most important part, in the eyes of my teammates, was that this was out-of-the-box. I wasn’t trying to implement regex or write a catch-all Replace statement or anything like that. And, thankfully (as you can see if you run the example), if the string passed in to HttpUtility.UrlDecode is not actually percent-encoded, nothing terrible happens. No errors or exceptions are thrown, and the string isn’t encoded (or anything odd like that). It remains un-transformed. That meant I could use HttpUtility.UrlDecode in one place to “fix” the return value where our code was retrieving the sometimes-encoded field, and while regression testing is still a thing, only a small amount of code changed.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.