How to use HttpClient to send a Request from a specific IP address? C#

前端 未结 1 1571
孤街浪徒
孤街浪徒 2020-12-20 01:09

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 request

相关标签:
1条回答
  • 2020-12-20 02:13

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

    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 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");
    
    0 讨论(0)
提交回复
热议问题