Practical .NET · Lesson 21

Escaping a URI query value

Encode data as one component instead of concatenating it as URI syntax.

How it works

A URI contains structured syntax: question marks, ampersands, equals signs, and other reserved characters have particular roles. A value supplied by a user can contain those same characters as ordinary data. When constructing a query, encode each value as a component so that its contents cannot accidentally become another separator or fragment of URI syntax.

Escaping a component is different from escaping an entire already-assembled URI. The separators that belong to the structure should remain separators, while the characters inside the value should be encoded where necessary. This lesson builds a prepared URI string only; it makes no network request. That keeps construction and transmission as separate actions with separate tests.

Walk through the example. The search term includes a hash sign, spaces, and an ampersand. EscapeDataString converts the term into an encoded component. The program appends that component after the fixed q= query key and constructs an absolute Uri. It then prints the URI and decodes the component to confirm the original search term can be recovered without turning its ampersand into a second parameter.

Watch the boundary. Do not encode an already encoded value repeatedly; each pass can encode the percent signs from the previous pass and change the meaning. Also do not treat URI escaping as validation of a destination's trustworthiness or as encryption. It preserves a component's data meaning within URI syntax, while destination policy and privacy remain separate concerns.

Practice independently. Create a query with two fixed keys and independently escaped values, one containing an equals sign and one containing a non-ASCII character. Verify the exact resulting string and decode each value. Test an empty value and a value containing a percent sign. Finally explain why escaping the whole finished query would also encode separators that the URI parser needs to recognize as structure.

A working example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

string term = "C# & .NET";
string encoded = Uri.EscapeDataString(term);
var address = new Uri("https://example.invalid/search?q=" + encoded);
Console.WriteLine(encoded);
Console.WriteLine(address.AbsoluteUri);
Console.WriteLine(Uri.UnescapeDataString(encoded));

Expected output

C%23%20%26%20.NET
https://example.invalid/search?q=C%23%20%26%20.NET
C# & .NET
Try this
Escape each data component once, leaving the URI’s intended separators intact.