UrlEncode
System.Web alternative
C# programming
URL encoding
ASP.NET development

How do you UrlEncode without using System.Web?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If you do not want to reference System.Web, you still have several valid ways to URL-encode data in .NET. The correct choice depends on whether you are encoding a query parameter value, a full URI component, or form-style content. In most modern code, Uri.EscapeDataString is the safest built-in replacement.

Use Uri.EscapeDataString for Query Parameter Values

When you need to encode a single value that will go into a query string, Uri.EscapeDataString is usually the right API.

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        string value = "Ada Lovelace & Alan Turing";
8        string encoded = Uri.EscapeDataString(value);
9
10        Console.WriteLine(encoded);
11    }
12}

This produces percent-encoded output suitable for embedding in a URL query parameter value.

Build a full query string safely like this:

csharp
1string query = "name=" + Uri.EscapeDataString("Ada Lovelace") +
2               "&city=" + Uri.EscapeDataString("New York");
3
4Console.WriteLine(query);

Encode values, not the full key=value&key2=value2 structure in one call.

Understand EscapeDataString Versus EscapeUriString

These two APIs are not interchangeable.

  • 'EscapeDataString is for individual data components'
  • 'EscapeUriString is for a broader URI string and is not ideal for arbitrary query values'

For query parameters, path fragments, or any user-provided piece of a URL, prefer EscapeDataString.

csharp
string unsafeValue = "a/b?c=d&x=y";
Console.WriteLine(Uri.EscapeDataString(unsafeValue));

This protects reserved characters that would otherwise alter URL meaning.

If You Need Form-Style Encoding

Some systems expect the application/x-www-form-urlencoded behavior where spaces become + instead of %20. EscapeDataString does not do that automatically.

Simple helper:

csharp
1using System;
2
3public static class UrlEncoding
4{
5    public static string FormEncode(string value)
6    {
7        return Uri.EscapeDataString(value).Replace("%20", "+");
8    }
9}
10
11Console.WriteLine(UrlEncoding.FormEncode("hello world"));

Use this only when the receiving system explicitly expects form-style encoding.

Use WebUtility.UrlEncode When Available

If your goal is only avoiding System.Web, another built-in option in many .NET environments is System.Net.WebUtility.

csharp
1using System;
2using System.Net;
3
4class Program
5{
6    static void Main()
7    {
8        string encoded = WebUtility.UrlEncode("Ada Lovelace & Alan Turing");
9        Console.WriteLine(encoded);
10    }
11}

This is often easier than writing custom logic and does not require the full System.Web dependency.

Avoid Writing a Full Manual Encoder Unless You Must

Manually encoding every byte yourself is possible, but it is easy to get wrong for Unicode and reserved characters. If you absolutely need custom behavior, operate on UTF-8 bytes explicitly.

csharp
1using System;
2using System.Text;
3
4public static class CustomEncoder
5{
6    public static string PercentEncodeUtf8(string value)
7    {
8        var bytes = Encoding.UTF8.GetBytes(value);
9        var sb = new StringBuilder();
10
11        foreach (byte b in bytes)
12        {
13            char ch = (char)b;
14            bool safe =
15                (ch >= 'a' && ch <= 'z') ||
16                (ch >= 'A' && ch <= 'Z') ||
17                (ch >= '0' && ch <= '9') ||
18                ch == '-' || ch == '_' || ch == '.' || ch == '~';
19
20            if (safe)
21                sb.Append(ch);
22            else
23                sb.Append('%').Append(b.ToString("X2"));
24        }
25
26        return sb.ToString();
27    }
28}
29
30Console.WriteLine(CustomEncoder.PercentEncodeUtf8("München"));

This should be a last resort, not a default approach.

Encode Only the Correct URL Part

A frequent bug is encoding an entire URL instead of only the dynamic component. For example, this is wrong:

csharp
string wholeUrl = Uri.EscapeDataString("https://example.com?q=hello world");

That encodes characters like : and / that are part of the URL structure. Instead, keep the structure literal and encode only the value:

csharp
string url = "https://example.com?q=" + Uri.EscapeDataString("hello world");
Console.WriteLine(url);

Common Pitfalls

One common mistake is using EscapeUriString when the actual need is encoding a query parameter value. Another is encoding an entire URL and breaking its structure. Developers also mix %20 and + semantics without checking which encoding the receiver expects. Hand-written encoders often mishandle Unicode because they work on characters instead of UTF-8 bytes. Finally, teams sometimes reimplement encoding even though Uri.EscapeDataString or WebUtility.UrlEncode already solves the problem.

Summary

  • You do not need System.Web to URL-encode values in .NET.
  • Use Uri.EscapeDataString for most query parameter and URI component encoding.
  • Use WebUtility.UrlEncode when available and appropriate.
  • Only use form-style + replacement when the receiver expects it.
  • Encode URL components, not whole URLs.
  • Avoid custom encoders unless you have a clearly defined nonstandard requirement.

Course illustration
Course illustration

All Rights Reserved.