01/26/2025
HttpClient type in .NET is one of the most dominant types to create network calls using HTTP protocol. One of the questions I face every time: how can I build the Uri
that is then passed to HttpRequestMessage
or HttpClient
to identify the resource to be requested. The API surface of these types accepts string
s and Uri
s, and Uri
s can be built from string
s.
Many line of business (LOB) applications also need to present links/URI that point out from the current application to some external resource. The parts of these URIs typically get concatenated from a well-known host, port, some path that may vary based on the resource and a query string.
In this post I am going explore different ways of creating URIs, focusing on creating the path segments. While schemas, hosts, ports, or query strings are going to be part of the final URI built, I am going to handle them as well formed constants for the purpose of this blog post. I do this because most applications define the base URIs in the settings, including the schema, the host and the port, such as https://localhost:5000/
. The path typically varies on the resource to be referenced. The query can also vary, but many RESTful APIs tend to choose path parameters and request bodies instead. However, the findings and concepts described in this post for the paths can generally applied for the other parts of the URI as well.
I am writing this blog post in the .NET 8 timeframe. This post uses the API surface of the preview versions of .NET 9.
Find out more