Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is HttpClient BaseAddress not working?

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?

like image 696
Timothy Shields Avatar asked May 02 '14 23:05

Timothy Shields


People also ask

How do I set HttpClient BaseAddress?

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.


1 Answers

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

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

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

like image 188
Timothy Shields Avatar answered Oct 22 '22 21:10

Timothy Shields