gpt4 book ai didi

c# - 是否可以在 C# 的 HttpClient 中设置自定义 DNS 解析器

转载 作者:行者123 更新时间:2023-12-04 01:38:31 25 4
gpt4 key购买 nike

我到底想要什么:

public static CustomDnsResolver : Dns 
{
.....
}

public static void Main(string[] args)
{
var httpClient = new HttpClient();
httpClient.Dns(new CustomDnsResolver());
}

基本上我只想在 HttpClient 中使用我的自定义 DNS 解析器而不是系统默认值,有什么方法可以实现吗?

最佳答案

您拥有的用例正是 Microsoft 构建 HttpClient 堆栈的原因。它允许您在 HttpMessageHandler 的帮助下将业务逻辑放在分层类中类(class)。您可以在 ms docs 中找到一些样本或 visualstudiomagazine

void Main()
{
var dnsHandler = new DnsHandler(new CustomDnsResolver());
var client = new HttpClient(dnsHandler);
var html = client.GetStringAsync("http://google.com").Result;
}

public class DnsHandler : HttpClientHandler
{
private readonly CustomDnsResolver _dnsResolver;

public DnsHandler(CustomDnsResolver dnsResolver)
{
_dnsResolver = dnsResolver;
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var host = request.RequestUri.Host;
var ip = _dnsResolver.Resolve(host);

var builder = new UriBuilder(request.RequestUri);
builder.Host = ip;

request.RequestUri = builder.Uri;

return base.SendAsync(request, cancellationToken);
}
}

public class CustomDnsResolver
{
public string Resolve(string host)
{
return "127.0.0.1";
}
}

关于c# - 是否可以在 C# 的 HttpClient 中设置自定义 DNS 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58547451/

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