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

时间:2023-04-11 14:25:44

我们都知道调用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,如下:

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

  <system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IBeautifulGirls" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:61909/BeautifulGirls.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IBeautifulGirls"
contract="BeautifulGirls.IBeautifulGirls" name="BasicHttpBinding_IBeautifulGirls" />
</client>
</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。

 var url=GetConfigvalue("BeautifulGirlsUrl");
var endpoint=GetConfigvalue("BeautifulGirls_EndPointName");
BeautifulGirlsClient client=new BeautifulGirlsClient(endpoint,url);
string jsonstr=client.GetBeautifulGirlsDetails("");

其实这里就是利用了

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

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