URL encoder/decoder · Guide
URL Encoder C#: Which .NET Method to Use
.NET offers three URL encoders with different behaviour, and choosing the wrong one produces values that work in a browser and fail against a strict API. Here is what separates them.
The three methods
using System;
using System.Net;
Uri.EscapeDataString("a b+c"); // "a%20b%2Bc" — RFC 3986
WebUtility.UrlEncode("a b+c"); // "a+b%2Bc" — form encoding
HttpUtility.UrlEncode("a b+c"); // "a+b%2Bc" — legacy, System.WebUri.EscapeDataString is the RFC 3986 encoder: space becomes %20, and it encodes !, ', (, ), * too. This is the one to use for path segments, query values and anything signed.
WebUtility.UrlEncode follows form rules: space becomes +. Correct for application/x-www-form-urlencoded bodies, wrong for path segments.
HttpUtility.UrlEncode is the legacy System.Web version, effectively the same as WebUtility. In new code prefer the other two.
Decoding
The decoders differ in the same way, and mixing them corrupts values containing a literal plus:
Uri.UnescapeDataString("a%20b%2Bc"); // "a b+c" — leaves + alone
WebUtility.UrlDecode("a+b%2Bc"); // "a b+c" — treats + as spaceDecode with the counterpart of whatever encoded the value. A phone number +380... decoded with WebUtility.UrlDecode after being encoded with EscapeDataString loses its plus.
Building URLs without the guesswork
For query strings, let a builder handle encoding rather than concatenating strings:
var query = new Dictionary<string, string?> { ["q"] = "salt & pepper", ["page"] = "2" };
var url = QueryHelpers.AddQueryString("/search", query); // Microsoft.AspNetCore.WebUtilities
// or, for full control
var builder = new UriBuilder("https://example.com/search")
{
Query = $"q={Uri.EscapeDataString("salt & pepper")}"
};One historical trap worth knowing: older .NET Framework versions had EscapeDataString limits on very long strings and different handling of %2F in paths. On modern .NET these are gone, but legacy code may contain workarounds that are now wrong.
Frequently asked questions
Which method should I default to?
Uri.EscapeDataString. It follows RFC 3986 and encodes spaces as %20.
Why did my plus sign turn into a space?
The value was decoded with a form decoder. Encode + as %2B, and match encoder to decoder.
Is HttpUtility.UrlEncode deprecated?
Not formally, but it belongs to System.Web. Use WebUtility or Uri methods in modern .NET.
Ready to try it?
Open the free browser-based URL encoder/decoder and apply what you just read — no sign-up, runs locally.
Open the URL encoder/decoder tool