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

后端 未结 11 934
小蘑菇
小蘑菇 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:28

    When you generate a web reference and click on the web reference in the Solution Explorer. In the properties pane you should see something like this:

    Web Reference Properties

    Changing the value to dynamic will put an entry in your app.config.

    Here is the CodePlex article that has more information.

    0 讨论(0)
  • 2020-11-28 09:29

    Change URL behavior to "Dynamic".

    0 讨论(0)
  • 2020-11-28 09:32

    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.

    0 讨论(0)
  • 2020-11-28 09:36

    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.

    0 讨论(0)
  • 2020-11-28 09:37

    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
          }
    
    0 讨论(0)
  • 2020-11-28 09:39

    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.
    0 讨论(0)
提交回复
热议问题