Change the url of a web service by reading from th

2019-04-15 14:57发布

问题:

This question already has an answer here:

  • What should be modified to change the URL of a web service in C#? 3 answers

I have a WCF app that consumes an asmx web service. I use the web service in a million places in the app:

    public string LogOnUser(string username, string password, string db)
    {
        var wsi = new ASMXServiceInterface();
        return wsi.LogIn();
      }

    public string GetNotes(string username, string password, string db)
    {
        var wsi = new ASMXServiceInterface();
        return wsi.GetNotes();
      }

    etc, etc etc...

Of course i want to set the url of the service in the contructor, but its auto generated in reference.cs and if i change it there, it works but if i update my reference ( and i will) its lost and i have to manually do it again:

      /// <remarks/>
    public ASMXServiceInterface()
    {
        this.Url = 
    System.Web.Configuration.WebConfigurationManager.AppSettings["RQTCSServiceURL"];
   }

The web service url will need to be dynamic because different versions of it have been implemented. How can i set the url of my web service once in my WCF project so the url of the service can be changed in the web.config without having to do it in reference.cs?

回答1:

You can do so by adding a key to your web.config like:

<add key="webserviceURL" value ="https://mywebservice.com/WebService.asmx" />

Then in your code, do something like:

private static WebService createWebService() {
        WebService service= new WebService();

        string url = ConfigurationManager.AppSettings["webserviceURL"];
        if ( !string.IsNullOrEmpty(url) ) {
            service.Url = url;
        }

        return service;
    }


回答2:

You can change the autogeneated url for webservice by converting the UrlBehaviour to dynamic

Please see example on how to do http://www.codeproject.com/Articles/12317/How-to-make-your-Web-Reference-proxy-URL-dynamic