.NET
URL Encoding
Forward Slash
Web Development
Programming

Url Encode Forward Slash (/) in .NET

Master System Design with Codemia

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

Introduction

To URL-encode a forward slash in .NET, use Uri.EscapeDataString("/") which produces %2F. Neither HttpUtility.UrlEncode nor WebUtility.UrlEncode encode forward slashes by default, so you need to choose the right method depending on whether the slash is data or a path delimiter.

What Is URL Encoding and Why Does It Matter?

URL encoding (percent-encoding) replaces unsafe or reserved characters with a % followed by two hex digits. The forward slash / is a reserved character defined in RFC 3986 as a path delimiter. When a slash appears as actual data rather than a path separator, leaving it unencoded causes servers to misinterpret URL structure.

For example, passing the date 04/01/2023 as a route parameter without encoding produces a URL like /api/dates/04/01/2023, which the server reads as three separate path segments instead of one value.

The Three Main Encoding Methods in .NET

.NET provides three methods that handle URL encoding differently. Understanding their behavior with forward slashes is critical.

This method encodes everything that is not an unreserved character per RFC 3986, including /:

csharp
1string date = "04/01/2023";
2string encoded = Uri.EscapeDataString(date);
3Console.WriteLine(encoded);
4// Output: 04%2F01%2F2023

Use this when the value will be embedded in a URL path segment or query parameter and slashes in the value are data, not delimiters.

WebUtility.UrlEncode (.NET Core / .NET 5+)

Available in System.Net, this method does not encode forward slashes:

csharp
1string date = "04/01/2023";
2string encoded = System.Net.WebUtility.UrlEncode(date);
3Console.WriteLine(encoded);
4// Output: 04/01/2023   (slash NOT encoded)

This is suitable for encoding query string values in modern .NET applications where slashes do not need encoding.

HttpUtility.UrlEncode (Legacy System.Web)

Available in System.Web, this method also does not encode forward slashes by default:

csharp
1string date = "04/01/2023";
2string encoded = System.Web.HttpUtility.UrlEncode(date);
3Console.WriteLine(encoded);
4// Output: 04%2f01%2f2023   (lowercase hex, only in some overloads)

Behavior varies by overload. Some overloads encode / and some do not. This inconsistency is a common source of bugs.

Comparison Table

MethodNamespaceEncodes /?.NET CoreBest For
Uri.EscapeDataStringSystemYes (%2F)YesPath segments, RFC-strict encoding
WebUtility.UrlEncodeSystem.NetNoYesQuery string values
HttpUtility.UrlEncodeSystem.WebVariesNo (requires package)Legacy ASP.NET WebForms
Uri.EscapeUriStringSystemNoYesFull URIs (rarely what you want)

Real-World Scenarios

Encoding a Path Parameter in a REST API

When a value containing slashes is part of a URL path, you must encode it:

csharp
1string filePath = "documents/reports/q1.pdf";
2string apiUrl = $"https://api.example.com/files/{Uri.EscapeDataString(filePath)}";
3Console.WriteLine(apiUrl);
4// Output: https://api.example.com/files/documents%2Freports%2Fq1.pdf

Without encoding, the server would try to match /files/documents/reports/q1.pdf against your route definitions and likely return a 404.

Encoding a Query String Value

For query parameters, slashes are usually safe, but encoding them prevents ambiguity:

csharp
1string searchTerm = "TCP/IP networking";
2string queryUrl = $"https://example.com/search?q={Uri.EscapeDataString(searchTerm)}";
3Console.WriteLine(queryUrl);
4// Output: https://example.com/search?q=TCP%2FIP%20networking

Building URLs with UriBuilder

UriBuilder does not automatically encode path components. Combine it with Uri.EscapeDataString:

csharp
1var builder = new UriBuilder("https://api.example.com");
2string folder = "my/folder";
3builder.Path = $"/api/resources/{Uri.EscapeDataString(folder)}";
4Console.WriteLine(builder.Uri);
5// Output: https://api.example.com/api/resources/my%2Ffolder

IIS and ASP.NET Configuration Gotcha

By default, IIS rejects URLs containing encoded slashes (%2F) in the path with a 400 Bad Request. To allow them, you need both a web.config setting and a registry change:

xml
1<!-- web.config -->
2<system.webServer>
3  <security>
4    <requestFiltering allowDoubleEscaping="true" />
5  </security>
6</system.webServer>

For .NET Framework on IIS, you also need this appSettings entry:

xml
<appSettings>
  <add key="aspnet:AllowRelaxedUriParsing" value="true" />
</appSettings>

In Kestrel (.NET Core / .NET 5+), encoded slashes in paths work by default without extra configuration.

Decoding Encoded Slashes

To decode %2F back to /, use the corresponding decode methods:

csharp
1string encoded = "04%2F01%2F2023";
2string decoded = Uri.UnescapeDataString(encoded);
3Console.WriteLine(decoded);
4// Output: 04/01/2023

Note that Uri.UnescapeDataString preserves %2F in some contexts when operating on full URIs. For path segments, always decode individual components, not the entire URL.

Common Pitfalls

  • Double encoding: Calling Uri.EscapeDataString on a string that is already encoded turns %2F into %252F. Always encode raw values, never pre-encoded strings.
  • Using Uri.EscapeUriString instead of Uri.EscapeDataString: EscapeUriString is designed for full URIs and does not encode reserved characters like /, ?, or #. It is almost never the right choice for encoding individual values. Microsoft deprecated it in .NET 6.
  • Assuming HttpUtility.UrlEncode handles slashes consistently: Its behavior varies across overloads and .NET versions. Prefer Uri.EscapeDataString for predictable results.
  • Forgetting IIS configuration: Even with correct encoding in your code, IIS may block requests containing %2F in the path unless you explicitly allow double escaping.
  • Case sensitivity of hex digits: %2F and %2f are semantically identical per RFC 3986, but some poorly implemented servers treat them differently. Uri.EscapeDataString always produces uppercase hex digits, which is the recommended form.

Summary

  • Use Uri.EscapeDataString to encode forward slashes in .NET. It produces %2F and is available in all .NET versions including .NET Core.
  • Neither WebUtility.UrlEncode nor HttpUtility.UrlEncode reliably encodes forward slashes.
  • Only encode slashes when they represent data, not when they serve as actual path delimiters.
  • On IIS, enable allowDoubleEscaping in web.config to accept %2F in URL paths.
  • Avoid Uri.EscapeUriString for encoding individual values. It is deprecated in .NET 6+.
  • Always encode raw strings to prevent double encoding.

Course illustration
Course illustration

All Rights Reserved.