silverlight 读取wcf服务 读取宿主端的config 良好的方法
在开发当中遇到很头疼的事情,就是每当要改动地图的服务的IP地址时,还要重新打开silverlight项目源代码,修改后重新编译,么么,这种是让人折磨呀。今天一天寻找方法,总算是解决了这个问题。
一、silverlight 读取wcf服务
1)在宿主端(也就是web端)添加(准备)wcf服务(service2.svc),其代码内容如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.Serialization; 5 using System.ServiceModel; 6 using System.Text; 7 8 namespace MyTestCongXML.Web 9 { 10 // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service2”。 11 // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Service2.svc 或 Service2.svc.cs,然后开始调试。 12 public class Service2 : IService2 13 { 14 public void DoWork() 15 { 16 } 17 public string hello() 18 { 19 return "你好"; 20 } 21 } 22 }
2)然后重新编译宿主端,而后在silverlight项目中添加引用web服务,添加web服务窗口中找到我们要引用的service2.svc,将其引用进来。然后删除引用时自动生成的xxxxx.ClientConfig文件;
3)在要用到此web服务的地方用代码自动引用wcf服务,具体代码如下
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Net; 6 using System.ServiceModel; 7 using System.ServiceModel.Channels; 8 using System.Windows; 9 using System.Windows.Browser; 10 using System.Windows.Controls; 11 using System.Windows.Documents; 12 using System.Windows.Input; 13 using System.Windows.Media; 14 using System.Windows.Media.Animation; 15 using System.Windows.Navigation; 16 using System.Windows.Shapes; 17 using System.Xml; 18 using System.Xml.Linq; 19 20 namespace MyTestCongXML 21 { 22 public partial class Home : Page 23 { 24 MyClass _myClass = new MyClass(); 25 26 public Home() 27 { 28 Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); 29 30 String myURL = Application.Current.Host.Source.ToString(); 31 int myindex = myURL.IndexOf("ClientBin"); 32 33 String url = myURL.Substring(0, myindex); 34 35 EndpointAddress endad = new EndpointAddress(url 36 +"service2.svc"); 37 38 ServiceReference1.Service2Client client = new ServiceReference1.Service2Client(binding, endad); 39 client.helloCompleted += client_helloCompleted; 40 client.helloAsync(); 41 InitializeComponent(); 42 43 44 45 } 46 47 void client_helloCompleted(object sender, ServiceReference1.helloCompletedEventArgs e) 48 { 49 tbText.Text = e.Result.ToString(); 50 } 51 52 53 54 protected override void OnNavigatedTo(NavigationEventArgs e) 55 { 56 57 } 58 59 } 60 }