問題起源:
很多時候為了業務層調用(后台代碼),一些公共服務就獨立成了WCF,使用起來非常方便,添加服務引用,然后簡單配置就可以調用了。
如果這個時候Web站點頁面需要調用怎么辦呢? 復雜的XML , 使用不方便 ,而且通信成本也比較高。 這時候有人受不了了,
於是就新建了一套WebAPI , Web頁面調用爽了。但是維護起來又麻煩了,一會兒WCF , 一會兒WebAPI 一段時間過后,可以想象已經相差甚遠了。
某一天同事A , 在業務層需要調用一個接口 ,發現它是WebAPI方式的 ,被迫沒辦法 , 去寫了一個DoRequest(..)的方法來封裝調用WebAPI ,
感覺比較痛苦,無端端增加了程序復雜度和工作量,同時還增加程序的風險點。
問題分析:
其實就是WCF不能兼容WebAPI輸出Json格式數據 , 如果可以寫一套接口就搞定了。
有沒有一個辦法能讓WCF服務又可以在業務層添加服務的方式調用,又可以在網頁上通過jQuery調用返回簡潔的Json數據呢?
如何解決:
WCF可以使用多個Endpoint,能不能再這個上面做文章呢?
首先,讓你的WCF接口支持Web請求,返回Json ,
System.ServiceModel.Web , 下有一個WebGetAttribute 可以幫我們實現:
[OperationContract] [WebGet(UriTemplate = "/yyy/{id}", ResponseFormat = WebMessageFormat.Json)] Product[] yyy(string id);
然后,修改服務配置:
<system.serviceModel> <services> <service name="xxx" behaviorConfiguration="Default"> <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="basicTransport" contract="Ixxx"/>/*提供WebGet服務用*/ <endpoint address="Wcf" binding="basicHttpBinding" contract="Ixxx"/>/*提供WCF服務 , 注意address='Wcf',為了區分開與WebGet的地址,添加引用之后會自動加上的*/ <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>/*元數據endpoint*/ </service> </services> <behaviors> <serviceBehaviors> <behavior name="Default"> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> <behavior name=""> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="web"> <webHttp helpEnabled="true"/> </behavior> </endpointBehaviors> </behaviors> <bindings> <webHttpBinding> <binding name="basicTransport"/> </webHttpBinding> </bindings> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel>
Web調用地址:http://ip:port/xxx.svc/yyy/id
Wcf服務地址會變為:http://ip:port/xxx.svc/Wcf
如此一來,前台后台的使用方式都不變,從此WCF一舉兩得,少了重復造輪子的時間與煩惱,省心不少。