Visual Studio makes it very easy to create and consume web services. This note explains how to set up the references to consume a web service with Visual Studio.NET.
In order to start using a web service, you should make a reference to this from Visual Studio,to acheive this,
- On your VS Solution Explorer, select your project, expand to References,Right click and click on Add Web References
- Type in URL of your web service and click on Go
- This will bring up your Web service's wsdl, you can change your web reference name to anything you want and click on Add Reference
Thats it, at this point, Visual Studio does all the work required (like creating your proxy class) and you are set to call your web service's web methods.
Now for some important and interesting observations!
The web reference you just created is a static reference, meaning it is always linked to the web service URL you just typed in. You can verify this by right clicking on your web reference to view the property sheet. You will notice that the URL Behavior is set to "static" with the Web Reference URL pointing to the URL you typed in. This is fine as long as you have only one environment (to TEST,QA,Stage, PRoduction....). But when you have to move your application through various environments in its life cycle, you will need to change this reference and rebuild the application. This leads us to the URL Behavior of "dynamic", when dynamic is set, your refrence.cs file (proxy) will include a property to read the URL from a Config File.
Code will look something like this...
public MyWebReference() {
string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["MyWebRef"];
if ((urlSetting != null)) {
this.Url = string.Concat(urlSetting, "");
}
else {
this.Url = "http://myWS/myWS.asmx";
}
}
Depending on the type of Visual Studion Project your web service client is, it works slightly different,
- If your app is a web application and making the web reference from your application, this App Setting entry will go into its web.config file
- If your app is windows application, making a dynamic reference will create an app.config entry and when built will be part of your app.exe.config
- If you are referencing web service from a Class library project, the entry should be made to the client of that class library, if web project is using this class library then entry should be in web config or if its a win app using the class library, app setting entry will goto app.config!
Happy coding !!
Cheers!