WCF兼容WebAPI输出Json格式数据,今后WCF一箭双雕

问题起源:web

  不少时候为了业务层调用(后台代码),一些公共服务就独立成了WCF,使用起来很是方便,添加服务引用,而后简单配置就能够调用了。spa

若是这个时候Web站点页面须要调用怎么办呢? 复杂的XML , 使用不方便 ,并且通讯成本也比较高。 这时候有人受不了了,code

因而就新建了一套WebAPI , Web页面调用爽了。可是维护起来又麻烦了,一下子WCF , 一下子WebAPI 一段时间事后,能够想象已经相差甚远了。orm

某一天同事A , 在业务层须要调用一个接口 ,发现它是WebAPI方式的 ,被迫没办法 , 去写了一个DoRequest(..)的方法来封装调用WebAPI ,blog

感受比较痛苦,无故端增长了程序复杂度和工做量,同时还增长程序的风险点。接口

 

问题分析:ip

  其实就是WCF不能兼容WebAPI输出Json格式数据 , 若是能够写一套接口就搞定了。get

  有没有一个办法能让WCF服务又能够在业务层添加服务的方式调用,又能够在网页上经过jQuery调用返回简洁的Json数据呢?string

 

如何解决:it

  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一箭双雕,少了重复造轮子的时间与烦恼,省心很多。

相关文章
相关标签/搜索