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

时间:2019-10-24 18:44:28

标签: c# .net dns dotnet-httpclient

我到底想要什么:

ShapeFactory.makeCube()

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

2 个答案:

答案 0 :(得分:0)

您拥有的用例正是Microsoft构建HttpClient堆栈的原因。它允许您借助HttpMessageHandler类将业务逻辑放入分层类中。您可以在ms docsvisualstudiomagazine

中找到一些示例
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";
    }
}

答案 1 :(得分:0)