Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

asp.net web api2 - How to use HttpClient to send a Request from a specific IP address? C#

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)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[ 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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...