本文介绍了为什么HttpClient的BaseAddress不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 考虑以下code,其中的 BaseAddress 定义局部URI路径。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");}我希望这执行 GET 要求 http://something.com/api/resource/7 。但事实并非如此。I expect this to perform a GET request to http://something.com/api/resource/7. But it doesn't.经过一番搜索,我发现这个问题的答案:的HttpClient与BaseAddress 。该建议是把 / 在末端的 BaseAddress 。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");}它仍然无法正常工作。这里的文档:HttpClient.BaseAddress这是怎么回事吗?推荐答案事实证明,出包括或不包括尾随或前导正斜杠上的四种可能的排列的 BaseAddress 和相对URI传递给 GetAsync 方法 - 仅的HttpClient 其他方法STRONG>一个置换工作。您必须将一个斜线结束时 BaseAddress ,您的不能将一个斜线的开始您的相对URI,如下面的示例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");}尽管我回答了我的问题,我想我会有助于解决在这里,因为,同样,这不友好的行为是无证。我的同事和我花了最多的一天试图解决这个问题最终被这个奇怪的的HttpClient 引起的问题。 这篇关于为什么HttpClient的BaseAddress不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-25 06:36