vs使用透明代理工厂方式调用HTTPS协议的WCF服务
作者:C/S框架网|www.csframewo  发布日期:2021-08-10 15:56:18
  vs使用透明代理工厂方式调用HTTPS协议的WCF服务

vs使用透明代理工厂方式调用HTTPS协议的WCF服务



透明代理工厂WCFFactory.Create方法:


C# Code:

/// <summary>
/// 动态创建WCF接口透明代理
/// </summary>
/// <typeparam name="T">WCF接口,如:ICommonService</typeparam>
/// <param name="uri">URI地址</param>
/// <returns></returns>
public static T Create<T>(string uri = "") where T : class
{
  
//获取接口的URI地址,必须是主程序的App.config配置文件
  
if (String.IsNullOrWhiteSpace(uri))
  {
    
//获取WCF接口的名称,如:ICommonService
    
string iName = typeof(T).Name;
    uri
= System.Configuration.ConfigurationManager.AppSettings[iName];
  }
  
  
//获取协议配置并创建实例,必须是主程序的App.config配置文件
  
var myBinding = new WSHttpBinding("WSHttpBinding");
  
var myEndpoint = new EndpointAddress(new Uri(uri));
  
var myChannelFactory = new ChannelFactory<T>(myBinding, myEndpoint);
  
  
//创建WCF通道
  
T instance = myChannelFactory.CreateChannel();
  
  
return instance;
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




测试调用WCF接口:


C# Code:

private void button1_Click(object sender, EventArgs e)
{
  
try
  {
    
var svc = WCFFactory.Create<MyCommonService.ICommonService>(txtUrl.Text);//创建WCF接口实例
    

    
byte[] loginTicket = GetLoginer();
    
    
var no = svc.GetDataSN(loginTicket, "AA", true);
    
    (svc
as ICommunicationObject).Close();//关闭WCF服务
    

    MessageBox.Show(no);
  }
  
catch (Exception ex)
  {
    
throw ex;
  }
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



App.Config文件:



XML Code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>

<!--测试界面的2种场景,分别对应下面的配置, 必须注释掉其中一种-->

<!-- 【添加服务引用】创建的配置
<wsHttpBinding>
<binding name="WSHttpBinding_ICommonService">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</wsHttpBinding>
-->

<!--【透明代理工厂】自定义binging, 名称:WSHttpBinding-->
<wsHttpBinding>
<binding name="WSHttpBinding">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</wsHttpBinding>

</bindings>
<client>
<endpoint address="https://cs5.manonwo.com/CommonService.svc"
binding
="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICommonService"
contract
="MyCommonService.ICommonService" name="WSHttpBinding_ICommonService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>

//来源:C/S框架网 | www.csframework.com | QQ:23404761




C/S框架网|原创精神.创造价值.打造精品


扫一扫加作者微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务
上一篇 下一篇