如何使用HttpClient从特定IP地址发送请求? C#

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

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

[这将是一个hacky代码,因为没有方法/属性来访问ServicePoint ]

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

HttpClientHandler SetServicePointOptions(HttpClientHandler handler) { var field = handler.GetType().GetField("startRequest", BindingFlags.NonPublic| BindingFlags.Instance); var startRequest = (Action)field.GetValue(handler); Action 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是您在问题中链接的那个。 根据需要修改它。 现在你可以使用这种方法了

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