教你如何在实战项目中使用WCF

我们都知道调用WCF直接在Service References中引用可以远程调用的WCF Url就行了。

但是我们想过没,在Development环境中可以这样做,但是QA、UAT、Production上我们怎么做呢?

WCF的通信方式主要有Http和Tcp,这次我们用Http。

好了,接下来老赵给你一个ideal,不算good。

1.新建一个WCF Service —‘BeautifulGirls.svc ',定义一个方法GetBeautifulGirlsDetails(string phoneNumber);

实现功能就是通过手机号获取‘美女’的详细信息。

2.在新建一个solution,引用wcf url,会自动生成一段References code和在web.config中添加一段serviceModel code,如下:

 1  <system.serviceModel>
 2     <bindings>
 3       <basicHttpBinding>
 4         <binding name="BasicHttpBinding_IBeautifulGirls" />
 5       </basicHttpBinding>
 6     </bindings>
 7     <client>
 8       <endpoint address="http://localhost:61909/BeautifulGirls.svc"
 9         binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IBeautifulGirls"
10         contract="BeautifulGirls.IBeautifulGirls" name="BasicHttpBinding_IBeautifulGirls" />
11     </client>
12   </system.serviceModel>

其中的原理我就不多说了,现在我们需要做的是将那段自动生成的References code放到一个class -BeautifulGirlsDefinition.cs中。

3.在appsetting中添加如下配置:

    <!-- Real name check -->
    <add key="BeautifulGirls_EndPointName" value="BasicHttpBinding_IBeautifulGirls"/>
    <add key="BeautifulGirlsUrl" env="Development"     value="http://hddcwiweb.dev:61909/BeautifulGirls.svc"/>
    <add key="BeautifulGirlsUrl" env="QA"            value="http://hddcwiweb.qa:61909/BeautifulGirls.svc"/>
    <add key="BeautifulGirlsUrl" env="UAT"             value="http://hddcwiweb.uat:61909/BeautifulGirls.svc"/>
    <add key="BeautifulGirlsUrl" env="Production"         value="http://hddcwiweb.prod:61909/BeautifulGirls.svc""/>

 4.读取配置文件中endpoint name和url。

1 var url=GetConfigvalue("BeautifulGirlsUrl");
2 var endpoint=GetConfigvalue("BeautifulGirls_EndPointName");
3 BeautifulGirlsClient client=new BeautifulGirlsClient(endpoint,url);
4 string jsonstr=client.GetBeautifulGirlsDetails("13288888888");

其实这里就是利用了

WCFClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)

 这个扩展方法,把不同环境的url配置到appsetting中,灵活利用。Over!下班。。。 

原文地址:https://www.cnblogs.com/kejie/p/6516049.html