[c#] How can I dynamically switch web service addresses in .NET without a recompile?

I have code that references a web service, and I'd like the address of that web service to be dynamic (read from a database, config file, etc.) so that it is easily changed. One major use of this will be to deploy to multiple environments where machine names and IP addresses are different. The web service signature will be the same across all deployments, just located elsewhere.

Maybe I've just been spoiled by the Visual Studio "Add Web Reference" wizard - seems like this should be something relatively easy, though.

This question is related to c# visual-studio web-services url wsdl

The answer is


Definitely using the Url property is the way to go. Whether to set it in the app.config, the database, or a third location sort of depends on your configuration needs. Sometimes you don't want the app to restart when you change the web service location. You might not have a load balancer scaling the backend. You might be hot-patching a web service bug. Your implementation might have security configuration issues as well. Whether it's production db usernames and passwords or even the ws security auth info. The proper separation of duties can get you into some more involved configuration setups.

If you add a wrapper class around the proxy generated classes, you can set the Url property in some unified fashion every time you create the wrapper class to call a web method.


If you are fetching the URL from a database you can manually assign it to the web service proxy class URL property. This should be done before calling the web method.

If you would like to use the config file, you can set the proxy classes URL behavior to dynamic.


If you are truly dynamically setting this, you should set the .Url field of instance of the proxy class you are calling.

Setting the value in the .config file from within your program:

  1. Is a mess;

  2. Might not be read until the next application start.

If it is only something that needs to be done once per installation, I'd agree with the other posters and use the .config file and the dynamic setting.


As long as the web service methods and underlying exposed classes do not change, it's fairly trivial. With Visual Studio 2005 (and newer), adding a web reference creates an app.config (or web.config, for web apps) section that has this URL. All you have to do is edit the app.config file to reflect the desired URL.

In our project, our simple approach was to just have the app.config entries commented per environment type (development, testing, production). So we just uncomment the entry for the desired environment type. No special coding needed there.


Just a note about difference beetween static and dynamic.

  • Static: you must set URL property every time you call web service. This because base URL if web service is in the proxy class constructor.
  • Dynamic: a special configuration key will be created for you in your web.config file. By default proxy class will read URL from this key.

I've struggled with this issue for a few days and finally the light bulb clicked. The KEY to being able to change the URL of a webservice at runtime is overriding the constructor, which I did with a partial class declaration. The above, setting the URL behavior to Dynamic must also be done.

This basically creates a web-service wrapper where if you have to reload web service at some point, via add service reference, you don't loose your work. The Microsoft help for Partial classes specially states that part of the reason for this construct is to create web service wrappers. http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.100).aspx

// Web Service Wrapper to override constructor to use custom ConfigSection 
// app.config values for URL/User/Pass
namespace myprogram.webservice
{
    public partial class MyWebService
    {
        public MyWebService(string szURL)
        {
            this.Url = szURL;
            if ((this.IsLocalFileSystemWebService(this.Url) == true))
            {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else
            {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }
    }
}

For me a Reference to a WebService is a

SERVICE REFERENCE

.

Anyway it's very easy. As someone said, you just have to change the URL in the web.config file.

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="YourServiceSoap" />
      </basicHttpBinding>
    </bindings>
    <client>
        **** CHANGE THE LINE BELOW TO CHANGE THE URL **** 
        <endpoint address="http://10.10.10.100:8080/services/YourService.asmx"
          binding="basicHttpBinding" bindingConfiguration="YourServiceSoap"
          contract="YourServiceRef.YourServiceSoap" name="YourServiceSoap" />
    </client>

Change URL behavior to "Dynamic".


open solition explorer

right click the webservice change URL Behavior to Dynamic

click the 'show all files' icon in solution explorer

in the web reference edit the Reference.cs file

change constructer

public Service1() {
        this.Url = "URL"; // etc. string  variable this.Url = ConfigClass.myURL
      }

I know this is an old question, but our solution is much simpler than what I see here. We use it for WCF calls with VS2010 and up. The string url can come from app settings or another source. In my case it is a drop down list where the user picks the server. TheService was configured through VS add service reference.

private void CallTheService( string url )
{
   TheService.TheServiceClient client = new TheService.TheServiceClient();
   client.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
   var results = client.AMethodFromTheService();
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to wsdl

Generating Request/Response XML from a WSDL How to generate xsd from wsdl How do you convert WSDLs to Java classes using Eclipse? How to get the wsdl file from a webservice's URL JSON, REST, SOAP, WSDL, and SOA: How do they all link together Difference between a SOAP message and a WSDL? SOAP PHP fault parsing WSDL: failed to load external entity? How to do a SOAP wsdl web services call from the command line Importing xsd into wsdl SoapUI "failed to load url" error when loading WSDL