C# - Set the URL per request using the HttpClient

This might seem trivial, but since I got the question the other day I might as well make a post about it. Using the HttpClient in C# you can set a baseAddress, but you do not have to use it.

You can use the baseAddress the following way:

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

The above will give you a 200 and fetch the content of my about page.

If you wanted to, you could use the same client to request another page on a completely different domain:

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

In the above we first make a request to the about page and then to a different domain (example.com) than the base address. This is possible because the base address only works with relative paths. However it can be hard to reason with the code if the same HttpClient is used throughout an application and used both with and without the base address. I would suggest either to not use the base address or to have a specific client per base address. Without the base address the above would be written as the following:

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

I hope this helps you out, let me know in the comments down below what you think!