HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpCritical

Why is HttpClient BaseAddress not working?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whyhttpclientworkingbaseaddressnot

Problem

Consider the following code, where the BaseAddress defines a partial URI path.

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");
}


I expect this to perform a GET request to http://something.com/api/resource/7. But it doesn't.

After some searching, I find this question and answer: HttpClient with BaseAddress. The suggestion is to place / on the end of the BaseAddress.

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");
}


It still doesn't work. Here's the documentation: HttpClient.BaseAddress What's going on here?

Solution

A simplified reasoning is that an absolute URL's base path -- not the full path -- goes up to the final slash. Relative URLs resolve from the base path.

; base path is http://something.com/api/resource/
http://something.com/api/resource/7

; base path is http://something.com/api/resource/
http://something.com/api/resource/

; base path is http://something.com/api/
http://something.com/api/resource

; base path is http://something.com/api/
http://something.com/api/

; base path is http://something.com/
http://something.com/api

; base path is http://something.com/
http://something.com/

; base path is http://something.com/
http://something.com


A different way to think about this that'll be familiar to many is how browsers combine ` with a page's current address. Browsers, HttpClient, and Uri` all follow the same URI specifications and will have similar behavior here.

The pattern you're trying to accomplish thus requires that ending slash on the base URI:

using HttpClient client = new();
client.BaseAddress = new Uri("http://something.com/api/");

using HttpResponseMessage response = await client.GetAsync("resource/7");
// ...

Code Snippets

; base path is http://something.com/api/resource/
http://something.com/api/resource/7

; base path is http://something.com/api/resource/
http://something.com/api/resource/

; base path is http://something.com/api/
http://something.com/api/resource

; base path is http://something.com/api/
http://something.com/api/

; base path is http://something.com/
http://something.com/api

; base path is http://something.com/
http://something.com/

; base path is http://something.com/
http://something.com
using HttpClient client = new();
client.BaseAddress = new Uri("http://something.com/api/");

using HttpResponseMessage response = await client.GetAsync("resource/7");
// ...

Context

Stack Overflow Q#23438416, score: 1449

Revisions (0)

No revisions yet.