如何使用HttpClient从特定IP地址发送请求? C# [英] How to use HttpClient to send a Request from a specific IP address? C#

查看:734
本文介绍了如何使用HttpClient从特定IP地址发送请求? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务器上有多个IP,并且希望选择使用HttpClient类从API获取/发布数据时要使用的IP中的哪一个. (甚至可以同时发送请求,但要使用2个IP,而不仅仅是一个IP)

I have multiple IPs on the server and would like to chose which one of those I want to use when using HttpClient class to get/post data from an API. (or to even send requests at the same time but utilise the 2 IPs and not just one)

我已经看到了一些使用HttpWebRequest的示例(这里)利用委托,但我想继续使用HttpClient实现.

I have seen some examples using HttpWebRequest (here) that utilises delegate but I would like to carry on using HttpClient implementation.

推荐答案

[这将是骇客代码,因为没有方法/属性可以访问 ServicePoint ]

[ This will be a hacky code, because there is no method/property to access the ServicePoint ]

您可以使用反射来访问基础的 ServicePoint ,如下所示 (由于没有公共/私有字段/属性可访问此值,因此我将钩住 startRequest 委托)

You can use reflection to access the underlying ServicePoint as below (Since there is no public/private field/property to access this value, I will hook the startRequest delegate)

HttpClientHandler SetServicePointOptions(HttpClientHandler handler)
{
    var field = handler.GetType().GetField("_startRequest", BindingFlags.NonPublic| BindingFlags.Instance); // Fieldname has a _ due to being private
    var startRequest = (Action<object>)field.GetValue(handler);

    Action<object> newStartRequest = obj =>
    {
        var webReqField = obj.GetType().GetField("webRequest", BindingFlags.NonPublic | BindingFlags.Instance);
        var webRequest = webReqField.GetValue(obj) as HttpWebRequest;
        webRequest.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);

        startRequest(obj); //call original action
    };

    field.SetValue(handler, newStartRequest); //replace original 'startRequest' with the one above

    return handler;
}

BindIPEndPointCallback 是您

BindIPEndPointCallback is the one you linked in your question. Modify it as you wish. Now you can use this method like

HttpClientHandler handler = SetServicePointOptions(new HttpClientHandler());
HttpClient client = new HttpClient(handler);
var str = await client.GetStringAsync("https://google.com");

这篇关于如何使用HttpClient从特定IP地址发送请求? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆