Parsing URLs

suggest change

.NET represents URLs with System.Uri. It parses a string into parts (scheme, host, port, path, query, fragment), validates it, normalizes it, and resolves relative links. You don't need any package for it. The related types are:

The examples are C# 14 / .NET 10 file-based programs (dotnet run app.cs), all run on Windows.

The parts of a URL

var uri = new Uri("https://alice:secret@www.example.com:8443/docs/guide/intro.html?lang=en&page=2#section-3");

Show("Scheme", uri.Scheme);
Show("UserInfo", uri.UserInfo);
Show("Host", uri.Host);
Show("Port", uri.Port);
Show("IsDefaultPort", uri.IsDefaultPort);
Show("Authority", uri.Authority);
Show("AbsolutePath", uri.AbsolutePath);
Show("Query", uri.Query);
Show("Fragment", uri.Fragment);
Show("PathAndQuery", uri.PathAndQuery);
Show("Segments", string.Join(" | ", uri.Segments));
Show("HostNameType", uri.HostNameType);

static void Show(string name, object value) => Console.WriteLine($"{name + ":",-15}{value}");
Scheme:        https
UserInfo:      alice:secret
Host:          www.example.com
Port:          8443
IsDefaultPort: False
Authority:     www.example.com:8443
AbsolutePath:  /docs/guide/intro.html
Query:         ?lang=en&page=2
Fragment:      #section-3
PathAndQuery:  /docs/guide/intro.html?lang=en&page=2
Segments:      / | docs/ | guide/ | intro.html
HostNameType:  Dns

Some details:

Accessing these properties on a relative Uri (for example new Uri("/a/b", UriKind.Relative)) throws InvalidOperationException. Check IsAbsoluteUri first if you don't know what kind you have.

Validating with Uri.TryCreate

new Uri(string) throws UriFormatException on invalid input. For user input use Uri.TryCreate, which returns false instead. The UriKind argument says what you expect:

string[] inputs =
[
    "https://example.com/path",
    "example.com/path",
    "/relative/path?x=1",
    "http://exa mple.com",
    "https://example.com:99999/",
    "mailto:bob@example.com",
    "javascript:alert(1)",
    "",
];

foreach (var s in inputs)
{
    bool abs = Uri.TryCreate(s, UriKind.Absolute, out Uri? a);
    bool rel = Uri.TryCreate(s, UriKind.Relative, out _);
    Console.WriteLine($"{"\"" + s + "\"",-32} absolute={abs,-5} relative={rel,-5} {(abs ? a!.Scheme : "")}");
}

try
{
    _ = new Uri("http://exa mple.com");
}
catch (UriFormatException e)
{
    Console.WriteLine($"UriFormatException: {e.Message}");
}
"https://example.com/path"       absolute=True  relative=False https
"example.com/path"               absolute=False relative=True  
"/relative/path?x=1"             absolute=False relative=True  
"http://exa mple.com"            absolute=False relative=False 
"https://example.com:99999/"     absolute=False relative=False 
"mailto:bob@example.com"         absolute=True  relative=False mailto
"javascript:alert(1)"            absolute=True  relative=False javascript
""                               absolute=False relative=True  
UriFormatException: Invalid URI: The hostname could not be parsed.

A user typing example.com/path without a scheme doesn't produce an absolute URL. If you want to accept that, prepend https:// when the string has no :// and try again.

A valid URL is not necessarily a web URL. mailto:, javascript: and file: URLs are all valid absolute URIs. If you're going to fetch the URL, put it in an <a href> or redirect to it, also check the scheme:

static bool IsHttpUrl(string? s, out Uri? uri) =>
    Uri.TryCreate(s, UriKind.Absolute, out uri)
    && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
    && !string.IsNullOrEmpty(uri.Host);

foreach (var s in new[] { "https://example.com/a", "HTTP://Example.COM", "ftp://example.com",
                          "javascript:alert(1)", "file:///etc/passwd", "https:/example.com", @"c:\temp\x.txt" })
{
    Console.WriteLine($"{s,-24} {(IsHttpUrl(s, out var u) ? "OK   " + u : "rejected")}");
}
https://example.com/a    OK   https://example.com/a
HTTP://Example.COM       OK   http://example.com/
ftp://example.com        rejected
javascript:alert(1)      rejected
file:///etc/passwd       rejected
https:/example.com       rejected
c:\temp\x.txt            rejected

The scheme check also protects against a platform difference. On Linux and macOS, Uri.TryCreate("/api/users", UriKind.Absolute, out _) returns true because /api/users is an absolute Unix file path, which becomes file:///api/users. On Windows it returns false. With UriKind.RelativeOrAbsolute both platforms give a relative Uri.

Uri.IsWellFormedUriString is stricter than TryCreate. It rejects characters that should have been percent-encoded:

foreach (var s in new[] { "https://example.com/a b", "https://example.com/a%20b", "https://example.com/café", "https://example.com/?q=[1]" })
{
    Console.WriteLine($"{s,-30} TryCreate={Uri.TryCreate(s, UriKind.Absolute, out _),-5} IsWellFormed={Uri.IsWellFormedUriString(s, UriKind.Absolute)}");
}
https://example.com/a b        TryCreate=True  IsWellFormed=False
https://example.com/a%20b      TryCreate=True  IsWellFormed=True
https://example.com/café       TryCreate=True  IsWellFormed=True
https://example.com/?q=[1]     TryCreate=True  IsWellFormed=False

Usually TryCreate is what you want: browsers accept the same sloppy input, and Uri encodes it for you.

Normalization: OriginalString, AbsoluteUri and ToString

Uri normalizes what it parses. It lowercases the scheme and host, drops the default port, resolves . and .. segments, decodes percent-encoded unreserved characters (%7E becomes ~, %41 becomes A) and encodes characters that aren't allowed. There are three ways to get the string back, and they differ:

var uri = new Uri("HTTPS://Example.COM:443/a/./b/../c%7E/caf%C3%A9 menu?q=a b&x=%41#Top");

Console.WriteLine($"OriginalString: {uri.OriginalString}");
Console.WriteLine($"AbsoluteUri:    {uri.AbsoluteUri}");
Console.WriteLine($"ToString():     {uri}");
Console.WriteLine($"AbsolutePath:   {uri.AbsolutePath}");
Console.WriteLine($"LocalPath:      {uri.LocalPath}");
Console.WriteLine($"Query:          {uri.Query}");
OriginalString: HTTPS://Example.COM:443/a/./b/../c%7E/caf%C3%A9 menu?q=a b&x=%41#Top
AbsoluteUri:    https://example.com/a/c~/caf%C3%A9%20menu?q=a%20b&x=A#Top
ToString():     https://example.com/a/c~/café menu?q=a b&x=A#Top
AbsolutePath:   /a/c~/caf%C3%A9%20menu
LocalPath:      /a/c~/café menu
Query:          ?q=a%20b&x=A

Extracting several parts with GetComponents

GetComponents returns any combination of parts, with the escaping you choose. GetLeftPart returns everything up to a given part:

var uri = new Uri("https://user:pw@example.com:8080/a/b?x=1#frag");

Console.WriteLine(uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped));
Console.WriteLine(uri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.UriEscaped));
Console.WriteLine(uri.GetComponents(UriComponents.Path, UriFormat.Unescaped));
Console.WriteLine(uri.GetComponents(UriComponents.Query, UriFormat.UriEscaped));
// everything except user info and fragment
Console.WriteLine(uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.UserInfo & ~UriComponents.Fragment,
                                    UriFormat.UriEscaped));
// origin, as used by browsers for CORS
Console.WriteLine(uri.GetLeftPart(UriPartial.Authority));
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
https://example.com:8080
https://example.com:8080/a/b?x=1
a/b
x=1
https://example.com:8080/a/b?x=1
https://user:pw@example.com:8080
https://user:pw@example.com:8080/a/b

UriComponents.Path and UriComponents.Query don't include the /, ? delimiters. GetLeftPart keeps the user info, so if you log URLs or build an origin for CORS use SchemeAndServer, which removes credentials.

Resolving relative URLs

new Uri(baseUri, relative) resolves a link the way a browser does. This is what you need when following links found in a page (see Web scraping):

var page = new Uri("https://example.com/blog/2026/post.html?ref=home");

string[] links = ["other.html", "../archive/", "/about", "?page=2", "#comments",
                  "//cdn.example.net/app.js", "https://github.com/"];
foreach (var link in links)
{
    Console.WriteLine($"{link,-26} -> {new Uri(page, link)}");
}

Console.WriteLine();
// the trailing slash matters
Console.WriteLine(new Uri(new Uri("https://api.example.com/v1"), "users"));
Console.WriteLine(new Uri(new Uri("https://api.example.com/v1/"), "users"));
Console.WriteLine(new Uri(new Uri("https://api.example.com/v1/"), "/users"));
other.html                 -> https://example.com/blog/2026/other.html
../archive/                -> https://example.com/blog/archive/
/about                     -> https://example.com/about
?page=2                    -> https://example.com/blog/2026/post.html?page=2
#comments                  -> https://example.com/blog/2026/post.html?ref=home#comments
//cdn.example.net/app.js   -> https://cdn.example.net/app.js
https://github.com/        -> https://github.com/
https://api.example.com/users
https://api.example.com/v1/users
https://api.example.com/users

The last three lines show a common bug with HttpClient.BaseAddress, which resolves request URLs the same way. The base must end with / and the relative path must not start with /, otherwise the v1 part is dropped.

The reverse operation is MakeRelativeUri. IsBaseOf checks whether a URL is under a base:

var root = new Uri("https://example.com/docs/");
var file = new Uri("https://example.com/docs/api/uri.html");
var other = new Uri("https://example.com/blog/post.html");

Console.WriteLine(root.MakeRelativeUri(file));
Console.WriteLine(file.MakeRelativeUri(other));
Console.WriteLine(root.IsBaseOf(file));
Console.WriteLine(root.IsBaseOf(other));
api/uri.html
../../blog/post.html
True
False

Comparing URLs

Uri overrides == and Equals to compare normalized URLs, so case differences in the scheme and host, default ports and unnecessary escapes don't matter. Equality also ignores the fragment and the user info:

var a = new Uri("HTTP://EXAMPLE.com:80/a%41?x=1#one");
var b = new Uri("http://example.com/aA?x=1#two");
Console.WriteLine($"a == b: {a == b}");
Console.WriteLine($"same string: {a.ToString() == b.ToString()}");
Console.WriteLine($"Compare without fragment: " +
    Uri.Compare(a, b, UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped, StringComparison.Ordinal));
Console.WriteLine($"/A equals /a: {new Uri("http://example.com/A") == new Uri("http://example.com/a")}");
Console.WriteLine($"user info ignored: {new Uri("https://a:b@example.com/") == new Uri("https://example.com/")}");
a == b: True
same string: False
Compare without fragment: 0
/A equals /a: False
user info ignored: True

Paths are case-sensitive, as they should be. The query is compared as-is: ?a=1&b=2 and ?b=2&a=1 are different URLs. If you use URLs as dictionary keys (e.g. a crawler's visited set), normalize them first: use AbsoluteUri, strip the fragment and, if your application allows it, sort the query parameters.

Parsing the query string

Uri doesn't split the query into parameters. In any .NET app use HttpUtility.ParseQueryString. It returns a NameValueCollection with case-insensitive keys:

using System.Web;

var uri = new Uri("https://shop.example.com/search?q=red+shoes&size=42&tag=sale&tag=new&city=K%C3%B6ln&empty=&flag");

var query = HttpUtility.ParseQueryString(uri.Query);   // leading '?' is skipped

Console.WriteLine($"q     = {query["q"]}");
Console.WriteLine($"size  = {int.Parse(query["size"]!)}");
Console.WriteLine($"tag   = {query["tag"]}");
Console.WriteLine($"tags  = [{string.Join(", ", query.GetValues("tag")!)}]");
Console.WriteLine($"city  = {query["city"]}");
Console.WriteLine($"empty = \"{query["empty"]}\"");
Console.WriteLine($"flag  = {query["flag"] ?? "(null)"}, keys with null name: {query.GetValues(null)?.Length}");
Console.WriteLine($"color = {query["color"] ?? "(missing)"}");
Console.WriteLine($"Count = {query.Count}");
foreach (string? key in query.AllKeys)
{
    Console.WriteLine($"  {key ?? "(null)"}: {query[key]}");
}
q     = red shoes
size  = 42
tag   = sale,new
tags  = [sale, new]
city  = Köln
empty = ""
flag  = (null), keys with null name: 1
color = (missing)
Count = 6
  q: red shoes
  size: 42
  tag: sale,new
  city: Köln
  empty: 
  (null): flag

Things to watch for:

In ASP.NET Core you rarely parse the query yourself: HttpRequest.Query is already parsed, and minimal API and MVC parameters are bound from it. When you do have a raw string, use QueryHelpers.ParseQuery, which returns Dictionary<string, StringValues>:

#:sdk Microsoft.NET.Sdk.Web
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.WebUtilities;

// parse: returns Dictionary<string, StringValues>
var parsed = QueryHelpers.ParseQuery("?tag=sale&tag=new&q=red+shoes&city=K%C3%B6ln");
foreach (var (key, values) in parsed)
{
    Console.WriteLine($"{key}: {values} (count {values.Count})");
}
string[] tags = parsed["tag"]!;
Console.WriteLine(string.Join(" + ", tags));

// add parameters to a URL that may already have a query string
string url = QueryHelpers.AddQueryString("https://example.com/list?page=1", "q", "C# & .NET");
url = QueryHelpers.AddQueryString(url, new Dictionary<string, string?> { ["sort"] = "name", ["dir"] = null });
Console.WriteLine(url);

// QueryBuilder supports repeated keys
var qb = new QueryBuilder { { "tag", "a" }, { "tag", "b c" } };
qb.Add("ids", ["1", "2"]);
Console.WriteLine(qb.ToQueryString());

// QueryString is the type of HttpRequest.QueryString
QueryString qs = QueryString.Create("q", "x y") + QueryString.Create("n", "1");
Console.WriteLine(qs);
tag: sale,new (count 2)
q: red shoes (count 1)
city: Köln (count 1)
sale + new
https://example.com/list?page=1&q=C%23%20%26%20.NET&sort=name
?tag=a&tag=b%20c&ids=1&ids=2
?q=x%20y&n=1

#:sdk Microsoft.NET.Sdk.Web makes the ASP.NET Core shared framework available to a file-based program. In a web project these types are already referenced. AddQueryString skips parameters whose value is null.

Building and modifying URLs with UriBuilder

Never build URLs by concatenating unescaped strings. A value containing &, #, ? or a space breaks the URL or, worse, injects extra parameters. UriBuilder lets you set parts separately. Combined with HttpUtility.ParseQueryString(string.Empty), which creates an empty collection whose ToString() produces an encoded query string, you can build any URL:

using System.Web;

var builder = new UriBuilder("https://api.example.com/v2/search")
{
    Port = -1,   // -1 means "use the scheme's default port"
};
builder.Path += "/products";

var q = HttpUtility.ParseQueryString(string.Empty);
q["q"] = "C# & .NET";
q["city"] = "Köln";
q.Add("tag", "a/b");
q.Add("tag", "50%");
builder.Query = q.ToString();
builder.Fragment = "results";

Console.WriteLine(q.ToString());
Console.WriteLine(builder.Uri.AbsoluteUri);

// modify an existing URL: replace one parameter, keep the rest
var existing = new UriBuilder("https://example.com/list?page=3&sort=name&dir=asc");
var qs = HttpUtility.ParseQueryString(existing.Query);
qs["page"] = "4";
qs.Remove("dir");
existing.Query = qs.ToString();
Console.WriteLine(existing.Uri);
q=C%23+%26+.NET&city=K%c3%b6ln&tag=a%2fb&tag=50%25
https://api.example.com/v2/search/products?q=C%23+%26+.NET&city=K%C3%B6ln&tag=a%2fb&tag=50%25#results
https://example.com/list?page=4&sort=name

The collection's ToString() encodes spaces as + and uses lowercase hex. Both are valid and every server understands them.

UriBuilder has a trap with ports. When it parses a URL it stores the port explicitly, so changing the scheme keeps the old port:

var b = new UriBuilder("http://example.com:80/a?x=1");
Console.WriteLine(b.Uri);
Console.WriteLine(b.ToString());
b.Scheme = "https";
Console.WriteLine(b.Uri);
b.Port = -1;
Console.WriteLine(b.Uri);
http://example.com/a?x=1
http://example.com:80/a?x=1
https://example.com:80/a?x=1
https://example.com/a?x=1

Set Port = -1 whenever you change Scheme. Also note that UriBuilder.ToString() always includes the port. Use builder.Uri.AbsoluteUri to get the URL.

If you don't want System.Web, a small helper with Uri.EscapeDataString works just as well:

static string BuildUrl(string baseUrl, IEnumerable<KeyValuePair<string, string?>> parameters)
{
    var pairs = parameters
        .Where(p => p.Value is not null)
        .Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value!)}");
    string query = string.Join("&", pairs);
    if (query.Length == 0) return baseUrl;
    return baseUrl + (baseUrl.Contains('?') ? "&" : "?") + query;
}

string? category = null;
var url = BuildUrl("https://api.example.com/search", [
    new("q", "C# & .NET"),
    new("page", 2.ToString()),
    new("category", category),        // skipped
    new("from", new DateTime(2026, 10, 17).ToString("yyyy-MM-dd")),
]);
Console.WriteLine(url);
https://api.example.com/search?q=C%23%20%26%20.NET&page=2&from=2026-10-17

Format numbers and dates with CultureInfo.InvariantCulture (or an explicit format, as above), otherwise a server can receive 3,5 instead of 3.5 depending on the user's locale. The resulting string can be passed directly to HttpClient.GetAsync (see Creating and sending an HTTP GET request).

Percent-encoding functions

.NET has several encoding functions. They differ in how they encode spaces and which characters they leave alone:

using System.Net;
using System.Web;

string s = "a b&c=d/é?~*'+";

Console.WriteLine($"Uri.EscapeDataString:  {Uri.EscapeDataString(s)}");
Console.WriteLine($"WebUtility.UrlEncode:  {WebUtility.UrlEncode(s)}");
Console.WriteLine($"HttpUtility.UrlEncode: {HttpUtility.UrlEncode(s)}");
Console.WriteLine($"HttpUtility.UrlPathEncode: {HttpUtility.UrlPathEncode(s)}");

Console.WriteLine();
Console.WriteLine($"UnescapeDataString(\"a+b%20c\"): {Uri.UnescapeDataString("a+b%20c")}");
Console.WriteLine($"WebUtility.UrlDecode(\"a+b%20c\"): {WebUtility.UrlDecode("a+b%20c")}");
Uri.EscapeDataString:  a%20b%26c%3Dd%2F%C3%A9%3F~%2A%27%2B
WebUtility.UrlEncode:  a+b%26c%3Dd%2F%C3%A9%3F%7E*%27%2B
HttpUtility.UrlEncode: a+b%26c%3dd%2f%c3%a9%3f%7e*%27%2b
HttpUtility.UrlPathEncode: a%20b&c=d/%c3%a9?~*'+

UnescapeDataString("a+b%20c"): a+b c
WebUtility.UrlDecode("a+b%20c"): a b c

Uri.EscapeUriString is obsolete because it doesn't escape &, ? or # in the values you pass it.

International domains, IP addresses and file paths

var idn = new Uri("https://münchen.example/straße?q=ü");
Console.WriteLine($"Host:        {idn.Host}");
Console.WriteLine($"IdnHost:     {idn.IdnHost}");
Console.WriteLine($"AbsoluteUri: {idn.AbsoluteUri}");

var v6 = new Uri("http://[2001:db8::1]:8080/status");
Console.WriteLine($"Host:        {v6.Host}  ({v6.HostNameType})");
Console.WriteLine($"DnsSafeHost: {v6.DnsSafeHost}");
Console.WriteLine($"Port:        {v6.Port}");

var v4 = new Uri("http://127.0.0.1/");
Console.WriteLine($"Host:        {v4.Host}  ({v4.HostNameType}), IsLoopback={v4.IsLoopback}");

foreach (var s in new[] { "http://x", "https://x", "ftp://x", "ws://x", "wss://x" })
{
    Console.Write($"{new Uri(s).Scheme}={new Uri(s).Port} ");
}
Console.WriteLine();

var file = new Uri(@"C:\Users\me\My Docs\report.pdf");
Console.WriteLine($"{file.AbsoluteUri}  IsFile={file.IsFile}  LocalPath={file.LocalPath}");
Host:        münchen.example
IdnHost:     xn--mnchen-3ya.example
AbsoluteUri: https://münchen.example/stra%C3%9Fe?q=%C3%BC
Host:        [2001:db8::1]  (IPv6)
DnsSafeHost: 2001:db8::1
Port:        8080
Host:        127.0.0.1  (IPv4), IsLoopback=True
http=80 https=443 ftp=21 ws=80 wss=443 
file:///C:/Users/me/My%20Docs/report.pdf  IsFile=True  LocalPath=C:\Users\me\My Docs\report.pdf

Security: validating redirect URLs

A classic vulnerability is the open redirect: a login page accepts ?returnUrl=... and redirects there, so an attacker sends victims a link to your site that ends up on their phishing site. Allow only local paths or an explicit list of hosts, and compare the parsed host, never a substring of the string:

// Is it safe to redirect to returnUrl after login?
static bool IsLocalUrl(string? url)
{
    if (string.IsNullOrEmpty(url) || url[0] != '/') return false;
    if (url.Length == 1) return true;
    // "//evil.com" and "/\evil.com" are protocol-relative URLs pointing to another host
    return url[1] != '/' && url[1] != '\\';
}

var allowedHosts = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "example.com", "www.example.com" };

bool IsAllowedRedirect(string? url) =>
    IsLocalUrl(url)
    || (Uri.TryCreate(url, UriKind.Absolute, out var u)
        && u.Scheme == Uri.UriSchemeHttps
        && allowedHosts.Contains(u.IdnHost));

string[] tests = ["/account", "//evil.com", "/\\evil.com", "https://www.example.com/x",
                  "https://example.com.evil.net/", "https://evil.net/?https://example.com",
                  "https://example.com@evil.net/", "http://example.com/", "javascript:alert(1)"];
foreach (var t in tests)
{
    Console.WriteLine($"{t,-40} {(IsAllowedRedirect(t) ? "allowed" : "BLOCKED")}");
}

Console.WriteLine(new Uri("https://example.com@evil.net/").Host);
/account                                 allowed
//evil.com                               BLOCKED
/\evil.com                               BLOCKED
https://www.example.com/x                allowed
https://example.com.evil.net/            BLOCKED
https://evil.net/?https://example.com    BLOCKED
https://example.com@evil.net/            BLOCKED
http://example.com/                      BLOCKED
javascript:alert(1)                      BLOCKED
evil.net

The last line shows why url.StartsWith("https://example.com") is not a check: in https://example.com@evil.net/ the example.com part is the user name and the host is evil.net. Browsers treat \ like /, which is why /\evil.com must be rejected too. In ASP.NET Core MVC, Url.IsLocalUrl(returnUrl) and LocalRedirect() implement the local check for you.

When your server fetches URLs supplied by users (webhooks, link previews, image import), validating the host string isn't enough to prevent server-side request forgery: a public host name can resolve to 127.0.0.1 or 169.254.169.254. Resolve the name and check the IP addresses you actually connect to.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents