通过从web.config中读取来更改Web服务的URL

我有一个使用asmx Web服务的WCF应用程序。 我在应用程序的一百万个地方使用Web服务:

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... 

当然我想在构造函数中设置服务的url,但是它在reference.cs中自动生成,如果我在那里更改它,它可以工作,但如果我更新我的引用(我会)它丢失,我必须手动再来一遍:

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

Web服务URL需要是动态的,因为它的不同版本已经实现。 如何在我的WCF项目中设置我的Web服务的URL一次,这样可以在web.config中更改服务的url,而无需在reference.cs中进行更改?

你可以通过在web.config中添加一个键来实现:

  

然后在您的代码中,执行以下操作:

 private static WebService createWebService() { WebService service= new WebService(); string url = ConfigurationManager.AppSettings["webserviceURL"]; if ( !string.IsNullOrEmpty(url) ) { service.Url = url; } return service; } 

您可以通过将UrlBehaviour转换为动态来更改webservice的自动生成的URL

请参阅如何做的示例http://www.codeproject.com/Articles/12317/How-to-make-your-Web-Reference-proxy-URL-dynamic