HttpRequestMessage在多IP环境中配置IP

时间:2016-01-22 15:20:43

标签: c#

我在主机上有多个IP,并希望选择从HttpClientHttpRequestMessage建立连接时使用的IP。这可以在没有我自己编写简单的http客户端的情况下完成吗?

我在bind connect socket之前寻找相当于HttpClientset new.prdId = concat(new.prdCode, new.prdRevise, new.prdMfgNmbr) ...或替代。

1 个答案:

答案 0 :(得分:2)

因此,如果您在Windows计算机上使用默认的HttpClient邮件处理程序,HttpClient将使用.Net HttpWebRequest来完成其工作。反过来,依赖于ServicePointManager来提供ServicePoint来管理与URI的连接。对于任何域,您可以挂钩其ServicePoint以更改它绑定到IPEndPoint的方式。

如果您使用您尝试连接的URI并找到其ServicePoint

var sp = ServicePointManager.FindServicePoint(uri);

然后你可以:

var sp = ServicePointManager.FindServicePoint(new Uri("http://www.google.com"));
sp.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) => {
    IPAddress adapterIpAddress = //your chosen adapter's IP address
    return new IPEndPoint(adapterIpAddress, 0);
};

如果你想获得真正的爵士乐,你可以将它折叠成DelegatingHandler,以便HttpClient为你处理一切:

public class RebindingHandler : DelegatingHandler
{
    private BindIPEndPoint bindHandler;
    public RebindingHandler(IEnumerable<IPAddress> adapterAddresses, 
                            HttpMessageHandler innerHandler = null)
        : base(innerHandler ?? new WebRequestHandler())
    {
        var addresses = adapterAddresses.ToList();
        if(!addresses.Any())
        {
            throw new ArgumentException();
        }
        var idx = 0;
        bindHandler = (servicePoint, remoteEndPoint, retryCount) => {
            int i = Interlocked.Increment(ref idx);
            uint i2 = unchecked((uint)i);
            int index = (int)(((long)i2) % addresses.Count);

            IPAddress adapterIpAddress = addresses[index];
            return new IPEndPoint(adapterIpAddress, 0);
        };
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var sp = ServicePointManager.FindServicePoint(request.RequestUri);
        sp.BindIPEndPointDelegate = bindHandler;
        var httpResponseMessage = await base.SendAsync(request, cancellationToken);
        return httpResponseMessage;
    }
}

然后你可以:

var addresses = new List<IPAddress>(); //this contains your adapter addresses
var client = new HttpClient(new RebindingHandler(addresses));

当你使用client时,内部处理程序将自动注册相关的ServicePoint以使用围绕一堆IPEndPoints旋转的BindIPEndPoint。