I used HttpClient in the code for a while and always believed that its use of Uris led to some fragility in my implementation. Most service endpoint base addresses are in the app./web.config file. As a result, they can be easily changed.
I found that when using these endpoint lines to create a Uri , if they don't end with / , I get really elusive behavior. When calling GetAsync() with the / -terminated BaseAddress BaseAddress , a non-concatenated URL that is sent by the GET request often leaves a line after the final / in BaseAddress , or it discards the line preceding the first / in GetUri.
For instance:
BaseAddress : http://test/serviceEndpoint
GetUri : api/customer
When HttpClient.GetAsync() is called with this GetUri , it will try to get from http://test/api/customer . If I close BaseAddress with / , everything works as expected.
My problem is that BaseAddress is configuration-controlled and puts a comment in the .config file saying "Make sure you complete all the service urls with / !". this is a really fragile decision.
So, I'm used to using the following code in my entire HttpClient construct:
var service = settings.GetValue("ServiceBaseUrl"); var serviceUri = !service.EndsWith("/") ? new Uri(service + "/") : new Uri(service); _client = new HttpClient { BaseAddress = serviceUri };`
While it is not fragile, it feels repetitive to have it in every HttpClient constructor. Is there anything in HttpClient or Uri that I can use to avoid this pattern?
source share