C# - How to set a BaseAddress using the HttpClient

If you would rather work with relative URLs than absolute URLs you can use the BaseAddress property of the HttpClient. All you have to do is set the BaseAddress on the HttpClient:

var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://peterdaugaardrasmussen.com/");
var response = await httpClient.GetAsync("about/");

That is basically all there is to it. However there are some pitfalls, 1) the BaseAddress must end with a / and the relative path given cannot start with a /. For example the below will give a 404:

var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://peterdaugaardrasmussen.com/2022");
var response = await httpClient.GetAsync("/05/08/csharp-set-the-url-per-request-using-httpclient/");

But this will work:

var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://peterdaugaardrasmussen.com/2022/");
var response = await httpClient.GetAsync("05/08/csharp-set-the-url-per-request-using-httpclient/");

In some scenarios it might work with whatever permutation you use of having / in the absolute or relative path, but having the / at the end of the base address seems to work all the time.

The base address only applies to relative paths, if the path given in the request is absolute it will disregard the base address. Thereby you can make calls using HttpClient to other domains than the base address - see this post for more examples.

I hope you found this helpful, please leave a comment down below if you did :)