为什么HttpClient的BaseAddress不工作?工作、HttpClient、BaseAddress

2023-09-02 01:40:00 作者:繁华落尽、如梦无痕

考虑以下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 引起的问题。