How to bind a WCF Http client to a specific outbou

2020-07-17 15:32发布

I want my request to go out through a specific IP Addresses. Is there a way to do that in WCF. The explanation of why I need this is a little long winded so i'd rather not get into that.

Here is sample code

string ipAddress = "192.168.0.32";
IService service;
ChannelFactory<IOmlService> factory = new ChannelFactory<IService>(new BasicHttpBinding(), new EndpointAddress("http://" + IPAddress + ":6996/IService"));
service = factory.CreateChannel();
service.Test();

Here is an example scenario to explain exactly what i'm looking for. Let's say I have two IPs on my machine (192.168.0.30 and 192.168.0.31). Both of them can hit 192.168.0.32. If i run this code now, it will hit the IP (.32) from any of my IPs (.30 or .31). How can i force it to go through a specific IP of mine (say .30). Is there any way to do that using WCF?

3条回答
来,给爷笑一个
2楼-- · 2020-07-17 15:45

The answer to the question is that it cannot be done. Here is the answer from a Microsoft MVP


So you want to let the client-side machine proactively select one of the network adpater interface(installed on it) to send out the WCF requests? I'm afraid this is out of WCF's control since WCF only focus on the following addresses:

** when behave as a host, we can choose to bind to a specific hostname/address to listen for client requests ** when behave as a client, we can choose the destination address/hostname to send request to.


查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-07-17 15:49

It seems to me that your problem should be solved by setting of an additional rote in the routing table. Try do following from the Command Prompt started with administrative rights:

route add 192.168.0.32 mask 255.255.255.255 192.168.175.30

If you want to save the route add -p switch additionally.

查看更多
甜甜的少女心
4楼-- · 2020-07-17 15:57

Are you trying to make something similar to IP-Sec on the Server so it only accepts request from specific IP addresses?

In this case, you need to implement IEndpointBehavior and IDispatchMessageInspector and:

    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        RemoteEndpointMessageProperty remoteAddress =
            (OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as
             RemoteEndpointMessageProperty);

        // validate ip here
        return null;
    }
查看更多
登录 后发表回答