gpt4 book ai didi

c# - 仅用于路径的 Uri 生成器

转载 作者:行者123 更新时间:2023-12-04 10:00:30 35 4
gpt4 key购买 nike

我偶然发现了 C# 中的 UriBuilder,它使代码更具可读性,而不是使用字符串插值或连接多个部分。例如,我可以执行以下操作:

var uriBuilder = new UriBuilder("https://github.com/dotnet/aspnetcore/search");
var parameters = HttpUtility.ParseQueryString(string.Empty);
parameters["q"] = "utf-8";
uriBuilder.Query = parameters.ToString();

哪个会给我 url https://github.com/dotnet/aspnetcore/search?q=utf-8。在处理多个查询参数时,这变得特别方便。但是,有一个限制。它只允许我构建 url,但我只需要它用于路径 + 查询参数。所以我想只构建 /dotnet/aspnetcore/search?q=utf-8 部分,而不是字符串插值或连接。

让我来解释一下为什么我需要这个。在我的服务部分,我有以下代码:

services.AddHttpClient("GitHub", client =>
{
client.BaseAddress = new Uri("https://github.com/);
});

现在我可以在某些服务类中执行此操作:

private readonly HttpClient _httpClient;

public RequestService(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient("GitHub");
}

当我发送请求时,基地址已经设置好,我只需要定义路径和url参数。直到现在我还没有找到比使用字符串插值更好的方法,这可能不是最好的方法。

public void SendRequest() {
var request = new HttpRequestMessage(HttpMethod.Get,
$"dotnet/aspnetcore/search?q={someString}");

var response = await client.SendAsync(request);
}

最佳答案

为了正确初始化包含其查询参数的路径,您可以使用内置的 QueryHelpersAddQueryString 扩展方法 ( docs ):

public void SendRequest() {
Dictionary<string, string> queryString = new Dictionary<string, string>
{
{ "q", "utf-8" }
};
string methodName = "dotnet/aspnetcore/search";
methodName = QueryHelpers.AddQueryString(methodName, queryString);
//methodName is "dotnet/aspnetcore/search?q=utf-8"

var request = new HttpRequestMessage(HttpMethod.Get, methodName);
var response = await this._httpClient.SendAsync(request);
}

不要忘记添加 using Microsoft.AspNetCore.WebUtilities;

还有一点,HttpRequestMessage 有两个参数化构造函数:

public HttpRequestMessage(HttpMethod method, string requestUri);
public HttpRequestMessage(HttpMethod method, Uri requestUri)

为了使用第二个构造函数,您可以轻松地使用:

Uri uri = new Uri(methodName, UriKind.Relative);
var request = new HttpRequestMessage(HttpMethod.Get, uri);

关于c# - 仅用于路径的 Uri 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61842738/

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