Is it possible to set custom DNS resolver in C#'s HttpClient

我是研究僧i 提交于 2021-01-27 20:07:40

问题


what exactly I want :

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

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

basically I just want to use my custom DNS resolver in HttpClient instead of System default, Is there any way to achieve it?


回答1:


The use case you have is exactly why Microsoft build the HttpClient stack. It allow you to put your business logic in layered class with the help of HttpMessageHandler class. You can find some sample in ms docs or 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";
    }
}


来源:https://stackoverflow.com/questions/58547451/is-it-possible-to-set-custom-dns-resolver-in-cs-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!