記錄:Web無引用無配置方式動態調用WCF服務

來源:互聯網
上載者:User

標籤:tar   color   detail   param   不同   throw   ebe   ddr   metadata   

       這幾年一直用WebApi較多,最近項目中有個需求比較適合使用WCF,以前也用過JQuery直接調用Wcf的,但是說實話真的忘了…

       所以這次解決完還是花幾分鐘記錄一下

 

       WCF服務端:宿主在現有Win服務中,在服務啟動時添加代碼 ,服務代碼就不用寫了,介面和實現按照契約實現即可

            
   private ServiceHost serviceHost = null; //服務宿主

        //啟動WCF服務 if (serviceHost != null) { serviceHost.Close(); } serviceHost = new ServiceHost(typeof(ControlService)); serviceHost.Open(); Toolkit.Log.Warn("WCF服務啟動");

 

      服務端ServiceModel配置:個人感覺也是最麻煩的地方,WCF本身支援多種通訊方式,所以配置較多,不過基本瞭解後也差不多

      詳細可參考:http://www.cnblogs.com/ingstyle/p/5711249.html

<?xml version="1.0" encoding="utf-8" ?><configuration>  <system.serviceModel>    <services>      <!-- This section is optional with the new configuration model           introduced in .NET Framework 4. -->      <service name="命名空間+類名"               behaviorConfiguration="ControlServiceBehavior">        <host>          <baseAddresses>            <add baseAddress="http://localhost:8000/ServiceModel/service.svc"/>          </baseAddresses>        </host>        <!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/ServiceModel/service  -->        <endpoint address=""                  binding="wsHttpBinding"                   contract="命名空間+介面名" />        <!-- the mex endpoint is exposed at http://localhost:8000/ServiceModel/service/mex -->        <endpoint address="mex"                  binding="mexHttpBinding"                  contract="IMetadataExchange" />      </service>    </services>    <behaviors>      <serviceBehaviors>        <behavior name="ControlServiceBehavior">          <serviceMetadata httpGetEnabled="true"/>          <serviceDebug includeExceptionDetailInFaults="False"/>        </behavior>      </serviceBehaviors>    </behaviors>  </system.serviceModel></configuration>

 

 啟動完後可訪問:http://localhost:8000/ServiceModel/service.svc 查看如:

 

   用戶端WCF服務調用封裝:

public class WCFHelper{    public WCFHelper()    {    }    public static object ExecuteMethod<T>(Binding bind, string pUrl, string pMethodName, params object[] pParams)    {        EndpointAddress address = new EndpointAddress(pUrl);        Binding bindinginstance = null;        bindinginstance = bind;        using (ChannelFactory<T> channel = new ChannelFactory<T>(bindinginstance, address))        {            T instance = channel.CreateChannel();            using (instance as IDisposable)            {                try                {                    Type type = typeof(T);                    MethodInfo mi = type.GetMethod(pMethodName);                    return mi.Invoke(instance, pParams);                }                catch (TimeoutException)                {                    (instance as ICommunicationObject).Abort();                    throw;                }                catch (CommunicationException)                {                    (instance as ICommunicationObject).Abort();                    throw;                }                catch (Exception vErr)                {                    (instance as ICommunicationObject).Abort();                    throw;                }            }        }    }}

 

由於是動態調用的,所以沒有任何配置,可以向下邊這樣直接使用:

        WSHttpBinding bind = new WSHttpBinding();//重點這兒,可以傳遞不同的Bind,和對應的服務端配置參數(如果參數和服務端不一致則會報錯)        WCFHelper.ExecuteMethod<IControlService>(bind,"http://localhost:8000/ServiceModel/service.svc", "ResetTerminal", new object[] { "參數" });

注意第一個參數需根據對應的WCF服務端配置對應

例如服務端是webHttpBinding,這兒也換成webHttpBinding bind=new webHttpBinding() 即可,這裡我使用的WSHttpBinding

如果有想瞭解JQuery調用WCF的方式請參考站長的部落格:http://www.cnblogs.com/dudu/archive/2009/07/14/1523082.html

 

記錄:Web無引用無配置方式動態調用WCF服務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.