WCF客户端简单动态配置服务地址

本来想实现WCF服务无论放到哪个机器上,我的客户端都不需要重新编译,只需要配置一个服务的地址即可。各种百度找到了很多解决方案。但都比较繁琐,(只要因为个人小菜看不懂太多的代码)我对WCF内部机制还不了解。单纯为了解决一个问题而去探索。对于知识的学习还是系统一些比较好。现在先分享一下这个简单使用的技巧。

WCF服务我是寄宿的控制台应用程序上的,不清楚怎么寄宿的筒靴可以查一些资料(我也是现学现卖~~)我写的都是最简单的,省略了很多设置。

控制台入口代码如下

static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(Service1)))
            {
                host.Open();
                Console.WriteLine("WCF中的HTTP监听已启动....");
                Console.ReadLine();
                host.Close();
            }
        }

是不是很简单,没有什么设置。注意在控制台应用程序中添加App.config。内容可以和WCF服务库中的配置一样。这样WCF服务的ABC才能通过控制台发布出来 

查看App.config会发现里面注释的很清楚。然后修改baseAddress就是发布出来的地址。

"1.0" encoding="utf-8" ?>


  
    "true" />
  
  
  
    
      "WcfServiceLibrary1.Service1">
        
          
            "http://localhost:87/Service1/" />
          
        
        
        
        "" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1">
          
          
            "localhost"/>
          
        
        
        
        
        "mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      
    
    
      
        
          
          "True"/>
          
          "False" />
        
      
    
  

View Code

这个localhost在不同的机器上运行就是不同的地址,所以在客户端就需要动态设置服务的地址。

客户端任然采用控制台应用程序添加服务引用

在程序入口处如下

 static void Main(string[] args)
        {
            string filepath = Directory.GetCurrentDirectory() + "\\config.xml";
            XmlDocument document = new XmlDocument();
            document.Load(filepath);
            XmlNodeList nodes = document.GetElementsByTagName("add");
            string url = "";
            for (int i = 0; i < nodes.Count; i++)
            {
                //获得将当前元素的key属性      
                XmlAttribute att = nodes[i].Attributes["key"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素      
                if (att.Value == "address")
                {
                    //对目标元素中的第二个属性赋值       
                    url = nodes[i].Attributes["value"].Value;
                    break;
                }
            }
            EndpointAddress address = new EndpointAddress(url);
            WSHttpBinding binding = new WSHttpBinding();
            ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(binding,address);
            string name= client.ShowName("西贝");
            Console.WriteLine(name);
            Console.ReadLine();
        }
View Code

读取配置文件中的地址。配置文件xml就在程序运行目录下。这样简单的设置就可以在服务地址发生改变的情况下,不用重新编译客户端。

配置文件如下

"1.0" encoding="utf-8"?>  
  
     
    "address" value="http://和服务地址匹配/Service1/" />  
    

大侠们,轻拍,疼~~~

      

转载于:https://www.cnblogs.com/xibei/p/4729265.html

你可能感兴趣的:(c#)