How can I dynamically switch web service addresses in .NET without a recompile?

后端 未结 11 964
小蘑菇
小蘑菇 2020-11-28 09:11

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

11条回答
  •  庸人自扰
    2020-11-28 09:47

    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;
                }
            }
        }
    }
    

提交回复
热议问题