• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > 总结C#动态调用WCF接口的两种方法

总结C#动态调用WCF接口的两种方法

作者:garfieldzf 字体:[增加 减小] 来源:互联网 时间:2017-05-28

garfieldzf 通过本文主要向大家介绍了c语言课程设计总结,c语言知识点总结,c语言实训总结,c语言基础知识总结,c语言实验总结等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

如何使用

1、第一种方式比较简单,而且也是大家喜欢的,因为不需要任何配置文件就可解决,只需知道服务契约接口和服务地址就可以调用。

2、使用Invoke的方式,但是需要在调用客户端配置WCF,配置后在Invoke类里封装服务契约接口即可。

客户端调用DEMO

//第一种方式
string url = "http://localhost:3000/DoubleService.svc";
IDoubleService proxy = WcfInvokeFactory.CreateServiceByUrl<IDoubleService>(url);
int result = proxy.Add(1, 3);
 
 
//第二种方式<br><br>int result1 = WCFInvoke.Invoke(t => t.Add(1, 3));<br><br>
<system.serviceModel>
  <behaviors>
   <endpointBehaviors>
    <behavior name="NewBehavior">
     <dataContractSerializer maxItemsInObjectGraph="65536000" />
    </behavior>
   </endpointBehaviors>
  </behaviors>
  <bindings>
   <basicHttpBinding>  
    <binding name="BasicHttpBinding_IDoubleService"
        closeTimeout="01:00:00"
        openTimeout="01:00:00"
        sendTimeout="01:00:00"
        receiveTimeout="01:00:00"
        maxBufferSize="2147483647"
        maxBufferPoolSize="524288"
        maxReceivedMessageSize="2147483647">
     <readerQuotas maxDepth="128" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
   </basicHttpBinding>
   <netMsmqBinding>
    <binding name="NetMsmqBinding_IAsyncSender">
     <security mode="None" />
    </binding>
   </netMsmqBinding>
  </bindings>
  <client>
   
   <endpoint address="http://localhost:3000/DoubleService.svc"
        binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IDoubleService"
        contract="DoubleStone.WebHost.IDoubleService"
        name="BasicHttpBinding_IDoubleService" />
  
  </client>
 </system.serviceModel>
</div>

第一种调用方式

public class WcfInvokeFactory
  {
    #region WCF服务工厂
    public static T CreateServiceByUrl<T>(string url)
    {
      return CreateServiceByUrl<T>(url, "basicHttpBinding");
    }
 
    public static T CreateServiceByUrl<T>(string url, string bing)
    {
      try
      {
        if (string.IsNullOrEmpty(url)) throw new NotSupportedException("This url is not Null or Empty!");
        EndpointAddress address = new EndpointAddress(url);
        Binding binding = CreateBinding(bing);
        ChannelFactory<T> factory = new ChannelFactory<T>(binding, address);
        return factory.CreateChannel();
      }
      catch (Exception ex)
      {
        throw new Exception("创建服务工厂出现异常.");
      }
    }
    #endregion
 
    #region 创建传输协议
    /// <summary>
    /// 创建传输协议
    /// </summary>
    /// <param name="binding">传输协议名称</param>
    /// <returns></returns>
    private static Binding CreateBinding(string binding)
    {
      Binding bindinginstance = null;
      if (binding.ToLower() == "basichttpbinding")
      {
        BasicHttpBinding ws = new BasicHttpBinding();
        ws.MaxBufferSize = 2147483647;
        ws.MaxBufferPoolSize = 2147483647;
        ws.MaxReceivedMessageSize = 2147483647;
        ws.ReaderQuotas.MaxStringContentLength = 2147483647;
        ws.CloseTimeout = new TimeSpan(0, 30, 0);
        ws.OpenTimeout = new TimeSpan(0, 30, 0);
        ws.ReceiveTimeout = new TimeSpan(0, 30, 0);
        ws.SendTimeout = new TimeSpan(0, 30, 0);
 
        bindinginstance = ws;
      }
      else if (binding.ToLower() == "nettcpbinding")
      {
        NetTcpBinding ws = new NetTcpBinding();
        ws.MaxReceivedMessageSize = 65535000;
        ws.Security.Mode = SecurityMode.None;
        bindinginstance = ws;
      }
      else if (binding.ToLower() == "wshttpbinding")
      {
        WSHttpBinding ws = new WSHttpBinding(SecurityMode.None);
        ws.MaxReceivedMessageSize = 65535000;
        ws.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.Windows;
        ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
        bindinginstance = ws;
      }
      return bindinginstance;
 
    }
    #endregion
  }
</div>

第二种调用方式

public class WCFInvoke
  {
    /// <summary>
    /// 你需要调用的服务契约
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="func"></param>
    /// <returns></returns>
    public static T Invoke<T>(Func<IDoubleService, T> func)
    {
      IServiceInvoker serviceInvoker=new WCFServiceInvoker();
      return serviceInvoker.InvokeService(func);
    }
  }
public interface IServiceInvoker
  {
    void InvokeService<T>(Action<T> invokeHandler) where T : class;
    TReslt InvokeService<T, TReslt>(Func<T, TReslt> invokeHandler) where T : class;
  }
 
public class WCFServiceInvoker:IServiceInvoker
  {
    private static readonly ChannelFactoryManager FactoryManager = new ChannelFactoryManager();
 
    private static readonly ClientSection ClientSection =
      ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
 
 
    public void InvokeService<T>(Action<T> invokeHandler) where T : class
    {
      KeyValuePair<string, string> endpointNameAddressPair = GetEndpointNameAddressPair(typeof(T));
      var arg = FactoryManager.CreateChannel<T>(endpointNameAddressPair.Key, endpointNameAddressPair.Value);
      var obj2 = (ICommunicationObject)arg;
      try
      {
        invokeHandler(arg);
      }
      finally
      {
        try
        {
          if (obj2.State != CommunicationState.Faulted)
          {
            obj2.Close();
          }
        }
        catch
        {
          obj2.Abort();
        }
      }
    }
 
 
    public TReslt InvokeService<T, TReslt>(Func<T, TReslt> invokeHandler) where T : class
    {
      KeyValuePair<string, string> endpointNameAddressPair = GetEndpointNameAddressPair(typeof(T));
      var arg = FactoryManager.CreateChannel<T>(endpointNameAddressPair.Key, endpointNameAddressPair.Value);
      var obj2 = (ICommunicationObject)arg;
      try
      {
        return invokeHandler(arg);
      }
      finally
      {
        try
        {
          if (obj2.State != CommunicationState.Closed || obj2.State != CommunicationState.Faulted)
          {
            obj2.Close();
          }
        }
        catch
        {
          obj2.Abort();
        }
      }
    }
 
    private KeyValuePair<string, string> GetEndpointNameAddressPair(Type serviceContractType)
    {
      var configException =
        new ConfigurationErrorsException(
          string.Format(
            "No client endpoint found for type {0}. Please add the section <client><endpoint name=\"myservice\" address=\"http://address/\" binding=\"basicHttpBinding\" contract=\"{0}\"/></client> in the config file.",
            serviceContractType));
      if (((ClientSection == null) || (ClientSection.Endpoints == null)) || (ClientSection.Endpoints.Count < 1))
      {
        throw configException;
      }
      foreach (ChannelEndpointElement element in ClientSection.Endpoints)
      {
        if (element.Con



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 总结C#动态调用WCF接口的两种方法
  • 总结C#删除字符串数组中空字符串的几种方法
  • 总结C#网络编程中对于Cookie的设定要点
  • 总结的5个C#字符串操作方法分享

相关文章

  • 2017-05-28C#实现进程管理的启动和停止实例
  • 2017-05-28Windows下C#的GUI窗口程序中实现调用Google Map的实例
  • 2017-05-28在C#中对TCP客户端的状态封装详解
  • 2017-05-28浅谈c#中const与readonly区别
  • 2017-05-28C#操作DataTable方法实现过滤、取前N条数据及获取指定列数据列表的方法
  • 2017-05-28c#注册客户端事件示例
  • 2017-05-28WPF字体或内容模糊的解决方法
  • 2017-05-28C#如何解析http报文
  • 2017-05-28重写、隐藏基类(new, override)的方法
  • 2017-05-28C#判断指定文件是否是只读的方法

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • C# 骑士飞行棋的源码(分享)
    • C#实现矩阵加法、取负、数乘、乘法的方法
    • C# 实现的图片盖章功能,支持拖拽、旋转、放缩、保存
    • C#通过IComparable实现ListT.sort()排序
    • C#给图片添加水印完整实例
    • C#实现XML与实体类之间相互转换的方法(序列化与反序列化)
    • C# Windows API应用之基于GetDesktopWindow获得桌面所有窗口句柄的方法
    • 轻松学习C#的异常处理
    • C#使用Word中的内置对话框实例
    • C# 观察者模式实例介绍

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有