zoukankan      html  css  js  c++  java
  • 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:  }
  • 相关阅读:
    置换群
    背包问题
    并查集
    链式前向星
    一个简单的金额平均分配函数(C#版)
    EasyUI ComboGrid的绑定,上下键和回车事件,输入条件查询
    Oracle表解锁语句
    如何将两个json合并成一个
    textbox只能输入数字或中文的常用正则表达式和验证方法
    C#注册表的读,写,删除,查找
  • 原文地址:https://www.cnblogs.com/jacle169/p/2810079.html
Copyright © 2011-2022 走看看