How to bind a WCF Http client to a specific outbou

2020-07-17 15:19发布

问题:

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?

回答1:

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.




回答2:

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;
    }


回答3:

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.