Wednesday, April 28, 2010

Consuming Web Services in .NET

http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspxYou have several options for consuming a web service in .NET.   The easiest way is to add a web reference to your project.  However, there are some drawbacks to this method.

Why I don't like using "add web reference"

1. Your local machine has to have access to the web service in question.  Normally this is not a problem, but I've had issues before where due to proxy servers or permissions (IE, you don't have access to the production instance of the web service) prevent .NET from accessing the URL.  You can work around this by consuming say a DEV version of the web service and then manually editing the files to point to the instance you really want to access.

2. Say you want to switch between the instance you want to access?  You have to change your service URL which requires the objects created to be re-generated.

Solution

My preference is to use the WSDL tool.   This tool should be pre-installed as part of your .NET install.  I normally copy the WSDLexe and its config to a directory to make it easier.

To use the tool, you really only have to specify the URL of the web service but I go a step further and specify the language I want the proxy code to be generated with.

From the command prompt all you have to do is "WSDL /l:CS http://www.mydomain.com/myservice.asmx" and hit enter and you're done.  (Without the quotes, of course).  This will generate a class file that you can add to your project.   The /l indicates which language to generate the web service wrapper with.  You have the option of several of the popular languages C# (CS), VB (VB), JavaScript (JS), VJS (J#).  See additional info for more about the optional parameters of this tool.

To use the service, you simply declare an instance of the class and then call the web methods like you would a normal class.  The tool is also smart about creating object definitons if the service defines them instead of returning a simple data type result.

Additional Info

I normally only have to make 1 tweak to the generated class which is to go into the constructor and add a string input parameter which I then set the "this.url" property inside the class to.  By default, you will see the url of the web service is hard coded.  Now you can store your URL in a web.config  or app.config file so that it can be changed easily to hit the different instances (dev, test, production) of your web service!

You actually can do some of this and more through the optional parameters on the WSDL tool but I personally hate writing exteremely long commands through the command-line.  However, you might need to specify the login/password and/or the proxy login/password if applicable to your situation.

I've included the link to the MSDN page that covers these options in detail.

MSDN: WSDL Tool

No comments:

Post a Comment