Monday, November 29, 2010

How to route your wcf service through your web proxy

This post just shows you a simple way to allow you allow your client applications connect to your wcf service through a proxy.

Lets look at the binding element for a simple service

<wsdualhttpbinding>
                <binding bypassproxyonlocal="false" clientbaseaddress="http://localhost:8188/clientCallback" closetimeout="00:01:00" hostnamecomparisonmode="StrongWildcard" maxbufferpoolsize="524288" maxreceivedmessagesize="265536" messageencoding="Text" name="WSDualHttpBinding_IMainService" opentimeout="00:01:00" receivetimeout="00:10:00" sendtimeout="00:01:00" textencoding="utf-8" transactionflow="false" usedefaultwebproxy="false">
<readerQuotas maxDepth="32" maxStringContentLength="18192" maxArrayLength="116384"
                        maxBytesPerRead="44096" maxNameTableCharCount="16384" />
<reliableSession ordered="false" inactivityTimeout="05:10:00" />
</binding>

</wsdualhttpbinding>

Notice that the useDefaultWebProxy property is set to false so as to allow the wcf proxy to use whichever proxy you now set. To allow your connection to go through a service all you have to do is add a proxyAddress property to your binding, so it becomes

<wsdualhttpbinding>
    <binding bypassproxyonlocal="false clientbaseaddress="http://localhost:8188/clientCallback"
 closetimeout="00:01:00"
 hostnamecomparisonmode="StrongWildcard"
 maxbufferpoolsize="524288"
 maxreceivedmessagesize="265536"
 messageencoding="Text" name="WSDualHttpBinding_IMainService"
 opentimeout="00:01:00" receivetimeout="00:10:00"
 sendtimeout="00:01:00" textencoding="utf-8" transactionflow="false"
 usedefaultwebproxy="false" proxyaddress="http://192.168.0.1:3028">
<readerQuotas maxDepth="32" maxStringContentLength="18192" maxArrayLength="116384"
                        maxBytesPerRead="44096" maxNameTableCharCount="16384" />
<reliableSession ordered="false" inactivityTimeout="05:10:00" />
</binding>

</wsdualhttpbinding>


but now what you just have is a service with a static proxy address. but lets say you want to do something fancy like let the user set and change his proxy, then you can just programmatically get acces to this binding and change the proxy address to whatever the user inputted.

you do this by

        WSDualHttpBinding binding = new WSDualHttpBinding("WSDualHttpBinding_IMainService");
        binding.ProxyAddress = new Uri(newProxyAddress);

where "WSDualHttpBinding_IMainService" is the name of your binding from your config file. Also newProxyAddress is the proxy address the user entered.

Lastly, remember that WCF has several bindings, not all bindings support a proxy, but your http binding types all allow proxies. So have fun using this.

P.S. if your proxy requires username and password, then check out this Link