请考虑以下代码,其中 BaseAddress
定义了部分URI路径 .
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");
}
我希望这会对 http://something.com/api/resource/7
执行 GET
请求 . 但事实并非如此 .
经过一番搜索,我找到了这个问题并回答:HttpClient with BaseAddress . 建议将 /
放在 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");
}
它仍然没有_893909的文档:HttpClient.BaseAddress这里发生了什么?
3 回答
事实证明,在
BaseAddress
中包含或排除尾随或前导斜杠的四种可能排列中,以及传递给GetAsync
方法的相对URI - 或者HttpClient
中的任何其他方法 - 只有 one 排列有效 . 您 must 在BaseAddress
的末尾放置斜杠,并且 must not 在相对URI的开头放置斜杠,如下例所示 .即使我回答了我自己的问题,我想我会在这里提供解决方案,因为这种不友好的行为再次没有记录 . 我的同事和我一天大部分时间都在努力解决最终由这种奇怪的问题引起的问题 .
参考分辨率由RFC 3986 Uniform Resource Identifier (URI): Generic Syntax描述 . 这正是它应该如何运作的 . 要保留基URI路径,您需要在基URI的末尾添加斜杠,并在相对URI的开头删除斜杠 .
如果基URI包含非空路径,则合并过程将丢弃它的最后一部分(在最后
/
之后) . 相关section:如果相对URI以斜杠开头,则称为绝对路径相对URI . 在这种情况下,合并过程忽略所有基URI路径 . 有关更多信息,请查看5.2.2. Transform References部分 .
或者 - 根本不要使用
BaseAddress
. 将整个网址放在GetAsync
()中