Using a wsewsdl2.exe generated proxy to talk to an ASMX web service using HTTP authentication

5 12 2005

So the scenario is that you have a pre-existing ASMX web service which uses standard HTTP authentication – right now, your code to hit the service using a wsdl.exe generated proxy might look something like this:

MyWonderfulServiceProxy.MyWonderfulService myService = new MyWonderfulServiceProxy.MyWonderfulService();
myService.Credentials = System.Net.CredentialCache.DefaultCredentials;
myService.MyGreatWebMethod();

Now let’s suppose you don’t want to use a wsdl.exe generated proxy, because you think they are plain ugly – and you would much rather use a nice clean wse2 SoapClient instead, so you crack open wsewsdl2.exe and enable wse2 on your client project.

MyWonderfulService myService = new MyWonderfulService();
myService.Credentials = … uh oh, hang on, we don’t have a credentials object, ahhhhhhhh *scream rant etc etc*

Well, before you throw in the towel, you have to understand how wse2 was designed.
It’s different from a regular ASMX web service in that wse2 is abstracted away from the transport layer – which means that a wse2 web service + client can communicate over many different channels, including TCP, MSMQ, MQSeries, etc.

Having said this, it makes perfect sense that the SoapClient doesn’t know anything about HTTP authentication credentials.  This doesn’t mean that you can’t set them though!

Let’s try again:

MyWonderfulService myService = new MyWonderfulService();
SoapHttpOutputChannel outputChannel = (SoapHttpOutputChannel) myService.Channel;
outputChannel.Options.Credentials = new System.Net.NetworkCredential(username, password, domain);
myService.MyGreatWebMethod();

Too easy!  You can see that instead of setting it within the proxy, we grab the channel, cast it to a SoapHttpOutputChannel and set the credentials within the Options property.

You should now be able to hit any ASMX web service using a wsewsdl2 proxy :)

You may also be asking – but where is all the fancy wse2 security features, and why would I even bother?  Well, the answer is – if you don’t have access to the service, then you can’t do much about it.  But if you are the owner/builder of the service, then you should probably consider using WS-Security instead.  This means that you will have to create a WS-Security header and add it to your SoapClient instead of using the credentials on the channel.