Recipe 14.5. Setting the URL of a Web Service at Runtime


Problem

You need to set the URL of the web service at runtime.

Solution

In the code-behind class for your page, set the URL property of the proxy class to the required URL after instantiating the proxy object, as shown here:

 

bookServices = New ExampleBookServices.CH14BookServicesVB bookServices.Url = _ "http://michaelk2/aspnetcookbook2vb/VBWebServices/CH14BookServicesVB.asmx"

bookServices = new ExampleBookServices.CH14BookServicesCS(); bookServices.Url = "http://michaelk2/aspnetcookbook2cs/CSWebServices/CH14BookServicesCS.asmx";

Better still, by storing the URL in web.config and setting the URL property of the proxy class at runtime from the web.config setting, you can avoid changing the code whenever the URL changes.

Discussion

The ability to configure an application without having to recompile its code every time you make a change in the location of its resources can be a time-saver. Since the URL for a web service can change, code your application to set the URL at runtime.

Whenever you add a web reference to a project, Visual Studio 2005 adds an entry to the <appSettings> section of the web.config containing the URL of the web reference, as shown here for the two web references added for the recipes in this chapter:

 

<appSettings> <add key="ExampleWebServices.CH14QuickWebServiceVB2" value="http://localhost/…/CH14QuickWebServiceVB2.asmx"/> <add key="ExampleBookServices.CH14BookServicesVB" value="http://localhost/…/CH14BookServicesVB.asmx"/> </appSettings>

<appSettings> <add key="ExampleWebServices.CH14QuickWebServiceCS2" value="http://localhost/…/CH14QuickWebServiceCS2.asmx"/> <add key="ExampleBookServices.CH14BookServicesCS" value="http://localhost/…/CH14BookServicesCS.asmx"/> </appSettings>

By using the URL in web.config and setting the URL property of the web service at runtime, no code changes are required when the URL changes:

 

bookServices.Url = _ ConfigurationManager.AppSettings.Item("ExampleBookServices.CH14BookServicesVB")

bookServices.Url = ConfigurationManager.AppSettings["ExampleBookServices.CH14BookServicesCS"];



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net