Calling a web service from behind a proxy
Once again I need to call out to an external web service from behind a proxy. Last time it was installing WATIR. This time it is just straight up .NET code, but somehow this configuration feels like something I have to learn over each time I see it, so I am going to burn it into my blog.
I am working through some hands on labs configuring the Unity Inversion Of Control Container. The labs come with a sample Stocks Ticker application which calls out to an external web service to get its updates. So when running behind a proxy that requires authentication, by default, what you will see when running this application is:
So I open up the MoneyCentralStockQuoteService.vb file, which defines the class that is calling the service, and find this constructor:
Public Sub New(ByVal implementation As MoneyCentralRemote) Me.implementation = implementation Me.Logger = New NullLogger End Sub
My first attempt to resolve the issue is this, setting up a manual proxy reference (an instance of WebProxy), which requires that I not only tell the proxy to use the default credentials but also provide the ISA server’s address.
Public Sub New(ByVal implementation As MoneyCentralRemote) Me.implementation = implementation 'wire up proxy information here Dim proxy As New Net.WebProxy("http://servername:8080") proxy.UseDefaultCredentials = True Me.implementation.Proxy = proxy Me.Logger = New NullLogger End Sub
This works and I can start working with the sample application:
However, hard-coding the server name seems less than terrific. I then remember that I can also configure the proxy settings in the app.config file like below, which also works.
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
What this approach reminds me of is that I shouldn’t have to hard-code my proxy server address. If the application can load up the correct default proxy information based on a config file setting it should be able to do so in code as well. There must be a way to wire into this default functionality in code. So, back to the syntax drawing board ... and I end up with this, somewhat cleaner option, that gets a reference to the default WebProxy by way of the WebRequest class:
Public Sub New(ByVal implementation As MoneyCentralRemote) Me.implementation = implementation
'set up proxy information here
implementation.Proxy = System.Net.WebRequest.DefaultWebProxy
implementation.Proxy.Credentials = Net.CredentialCache.DefaultCredentials
Me.Logger = New NullLogger End Sub
Of the three approaches, I strongly favor setting up the proxy settings in the configuration file, as it is specific to the environment. Are there any options that I missed?
© Copyright 2009 - Andreas Zenker