首页 文章

为什么HttpClient BaseAddress不起作用?

提问于
浏览
186

请考虑以下代码,其中 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 回答

  • 2

    事实证明,在 BaseAddress 中包含或排除尾随或前导斜杠的四种可能排列中,以及传递给 GetAsync 方法的相对URI - 或者 HttpClient 中的任何其他方法 - 只有 one 排列有效 . 您 mustBaseAddress 的末尾放置斜杠,并且 must not 在相对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");
    }
    

    即使我回答了我自己的问题,我想我会在这里提供解决方案,因为这种不友好的行为再次没有记录 . 我的同事和我一天大部分时间都在努力解决最终由这种奇怪的问题引起的问题 .

  • 423

    参考分辨率由RFC 3986 Uniform Resource Identifier (URI): Generic Syntax描述 . 这正是它应该如何运作的 . 要保留基URI路径,您需要在基URI的末尾添加斜杠,并在相对URI的开头删除斜杠 .

    如果基URI包含非空路径,则合并过程将丢弃它的最后一部分(在最后 / 之后) . 相关section

    5.2.3 . 合并路径上面的伪代码是指用于将相对路径引用与基URI的路径合并的“合并”例程 . 这可以通过以下方式完成:如果基URI具有已定义的权限组件和空路径,则返回由引用的路径连接的“/”组成的字符串;否则返回一个字符串,该字符串由附加到基URI路径的最后一段以外的所有路径的路径组件组成(即,排除基URI路径中最右侧“/”之后的任何字符,或者排除整个基URI路径它不包含任何“/”字符) .

    如果相对URI以斜杠开头,则称为绝对路径相对URI . 在这种情况下,合并过程忽略所有基URI路径 . 有关更多信息,请查看5.2.2. Transform References部分 .

  • 21

    或者 - 根本不要使用 BaseAddress . 将整个网址放在 GetAsync ()中

相关问题