Silverlight 同域WCF免跨域文件
生活随笔
收集整理的這篇文章主要介紹了
Silverlight 同域WCF免跨域文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在sl3使用wcf時常常會因為sl中調用了不同域的wcf服務而導至調用服務失敗,記得在很久以前sl當是只支持同域的訪問,那么讓我有一個想法,就是在sl引用時可以動態地取得當前sl所在的域,而wcf服務也必須同時部署到這個域下邊,只要在silverlight的.web工程里添加一個WCF-Enable即就可以最簡單的實現。
以下為實代碼部份:
引用的命名空間
1: using System.ServiceModel; 2: using System.ServiceModel.Channels;封裝一個方法
1: //定義一個client代理 2: static ServiceReference1.Service1Client client; 3:? 4: //定義一個返回一個client代理的方法,參數為wcf服務的.svc文件名 5: ServiceReference1.Service1Client getService(string serviceFileName) 6: { 7: //取得當前url地址 8: var url = Application.Current.Host.Source.AbsoluteUri; 9: //取得xap文件名 10: var fileName = System.IO.Path.GetFileName(url); 11: //切換成正式域名地址 12: var realyUrl = url.Replace("/ClientBin/" + fileName, ""); 13:? 14:? 15: //sl3中的wcf-enable使用的是customBinding 16: CustomBinding binding = new CustomBinding( 17: new BinaryMessageEncodingBindingElement(), 18: new HttpTransportBindingElement()); 19:? 20:? 21: //地址 22: EndpointAddress address; 23:? 24:? 25:? 26: if (serviceFileName == string.Empty) 27: { 28: //如果沒有輸入字符則使用默認的地址 29: address = new EndpointAddress(realyUrl + "/Service1.svc"); 30: } 31: else 32: { 33: //如果輸入了參數則使用參數生成地址 34: address = new EndpointAddress(realyUrl + "/" + serviceFileName); 35: } 36:? 37: if (client == null) 38: { 39: //如果client未建議,則新建一個client 40: client = new FunWCF.ServiceReference1.Service1Client(binding, address); 41: return client; 42: } 43: else 44: { 45: //client已建立,直接返回client 46: return client; 47: } 48:? 49: }使用測試
1: void MainPage_Loaded(object sender, RoutedEventArgs e) 2: { 3: //取得一個client實例 4: ServiceReference1.Service1Client svc = getService(string.Empty); 5: //異步調用DoWork完成事件 6: svc.DoWorkCompleted += (s1, e1) => { if (e1.Error == null && e1.Result != null) MessageBox.Show(e1.Result); }; 7: //異步調用DoWork 8: svc.DoWorkAsync(); 9: }轉載于:https://www.cnblogs.com/jacle169/archive/2012/12/09/2810079.html
總結
以上是生活随笔為你收集整理的Silverlight 同域WCF免跨域文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地平线4多少钱啊?
- 下一篇: 做试管婴儿一般几次才会成功?