Why is HttpClient BaseAddress not working?
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.
If base URI contains non-empty path, merge procedure discards it's last part (after last /
). Relevant section:
5.2.3. Merge Paths
The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:
- If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise
- return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.
if you are using httpClient.SendAsync() there is no string overload for giving relative Uris like the overloads for Get or other verb-specific methods.
But you can create relative Uri with giving UriKind.Relative as second param
var httpRequestMessage = new HttpRequestMessage
{
Method = httpMethod,
RequestUri = new Uri(relativeRequestUri, UriKind.Relative),
Content = content
};
using var httpClient = HttpClientFactory.CreateClient("XClient");
var response = await httpClient.SendAsync(httpRequestMessage);
var responseText = await response.Content.ReadAsStringAsync();