gpt4 book ai didi

c# - HttpClient在某些情况下修改BaseAddress

转载 作者:行者123 更新时间:2023-12-05 02:48:17 26 4
gpt4 key购买 nike

<分区>

在基本层面上,我应该能够在 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();

Fiddler 网址:

GET http://restcountries.eu/rest/v2 HTTP/1.1

我有一个本地 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();

Fiddler 网址:

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();

Fiddler 网址:

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));
}
}
}

输出

http://restcountries.eu/JsonPerson/GetApiPerson

http://restcountries.eu/Api/GetApiPerson

http://restcountries.eu/rest/v2

原来这东西好像跟它有点关系……

https://github.com/microsoft/referencesource/blob/f461f1986ca4027720656a0c77bede9963e20b7e/System/net/System/UriExt.cs#L742

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com