【发布时间】:2020-10-31 00:30:57
【问题描述】:
在基本层面上,我应该能够在HttpClient 上设置绝对BaseAddress,然后使用相对Uri 发送Http 请求。期望是相对 Uri 将附加到基地址以进行 Http 调用。在大多数情况下,它都会这样做。这个例子运行良好。
编辑:见底部。这似乎是 Uris 构建方式的奇怪行为。
var httpClient = new HttpClient() { BaseAddress = new Uri("http://restcountries.eu/rest/", UriKind.Absolute) };
var requestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri("v2", UriKind.Relative));
var httpResponseMessage = await httpClient.SendAsync(requestMessage);
var json = await httpResponseMessage.Content.ReadAsStringAsync();
提琴手网址:
GET http://restcountries.eu/rest/v2HTTP/1.1
我有一个本地 API。当我在本地 API 上运行等效的 API 时,调用会截断部分基地址(“Api”)。
var httpClient = new HttpClient() { BaseAddress = new Uri($"http://localhost/JsonPerson/Api", UriKind.Absolute) };
var requestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri("GetApiPerson", UriKind.Relative));
var httpResponseMessage = await httpClient.SendAsync(requestMessage);
var json = await httpResponseMessage.Content.ReadAsStringAsync();
提琴手网址:
GET http://localhost/JsonPerson/GetApiPerson HTTP/1.1
为什么要去掉“/Api”?
此代码命中本地 API 并且工作正常:
var httpClient = new HttpClient() { BaseAddress = new Uri($"http://localhost/JsonPerson/", UriKind.Absolute) };
var requestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri("Api/GetApiPerson", UriKind.Relative));
var httpResponseMessage = await httpClient.SendAsync(requestMessage);
var json = await httpResponseMessage.Content.ReadAsStringAsync();
提琴手网址:
GET http://localhost/JsonPerson/Api/GetApiPerson HTTP/1.1
这是一个奇怪的问题,我无法弄清楚为什么会出现这些不一致...对于本地和非本地 uri,是否对 uri 进行了不同的处理?我在这里错过了什么?
这是 .NET Core 3.1
看看这段代码,然后看看输出。这就是HttpClient 在幕后所做的事情。
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
var baseAddress = new Uri($"http://restcountries.eu/JsonPerson/Api", UriKind.Absolute);
var resourceUri = new Uri($"GetApiPerson", UriKind.Relative);
Console.WriteLine(new Uri(baseAddress, resourceUri));
baseAddress = new Uri($"http://restcountries.eu/JsonPerson", UriKind.Absolute);
resourceUri = new Uri($"Api/GetApiPerson", UriKind.Relative);
Console.WriteLine(new Uri(baseAddress, resourceUri));
baseAddress = new Uri($"http://restcountries.eu/rest/", UriKind.Absolute);
resourceUri = new Uri($"v2", UriKind.Relative);
Console.WriteLine(new Uri(baseAddress, resourceUri));
}
}
}
输出
原来这东西好像和它有关系……
【问题讨论】:
-
这看起来确实像一个错误。我已经尝试过遵循
HttpRequestMessage.RequestUriis used 的方法并很快放弃了 :) 也许值得向 .NET repro 报告。 -
我现在正在查看代码,但它太混乱了
-
不!问题要简单得多。它与 Url 连接。
-
只需添加一个斜线即可终止 Url 部分:
http://restcountries.eu/JsonPerson/Api/、http://restcountries.eu/JsonPerson/等 -
IMO 这很不直观,我们需要为
BaseAddress添加斜线。它在任何地方都有记录吗?请发布您的发现作为答案,很确定其他人会遇到这个问题,包括我:)
标签: c# .net api httpclient uri