I've just spent the last hour learning a ton about HttpClient (here and here and here and ...). And clearly I want to use IHttpClientFactory
to get any HttpClient
I need. But I have not seen a clear answer on one part.
95% of my HttpClient
requests will be to my Azure BLOB storage. So same URL for all those requests. I see some examples that do something like this:
services.AddHttpClient<GitHubClient>("GitHubClient.Version9", x => { x.BaseAddress = new Uri(GitHubConstants.ApiBaseUrl); });
Where it is creating a client with a specific base address. So a couple of questions about this:
- Is this a good idea and what is the advantage?
- Will I get the not updating DNS issue with this? I’m guessing the IP address of my Azure BLOB storage will be changing regularly.
- I still have to provide the URI for a specific file. So am I then just providing everything after the base? (This is a slight pain as I have these urls in the database as the full url - and they need to be that way.)
The whole idea behind the type client
AddHttpClient<GitHubClient>
is that you want to hide the http based communication from the rest of the world. TheGitHubClient
class can encapsulate all the following logic:From the consumer of the
GitHubClient
perspective it is all hidden. (S)he can only see strongly typed methods likeTask<List<Branch>> GetRemoteBranches()
Task<List<PullRequest>> GetPullRequests(PullRequestState stateFlag)
For further information I would recommend the following threads:
In case of .NET Core and .NET 5+ the
HttpClient
instances are short living whereas the underlyingHttpClientMessageHandler
are pooled and reused. You don't have to care about the DNS resolve issues any moreFor further information I would recommend the following threads:
Yes that's correct. If you have set up the
BaseAddress
then it will be always used as a prefix. So, in your requests you should only provide the relative url. Gladly you don't have to deal with the forward slashes, it will be resolved automatically. So, the bellow four code examples are issuing the same request againsthttps://httpstat.us/200
url.