這幾年一直用WebApi較多,最近項目中有個需求比較適合使用WCF,之前也用過JQuery直接調用Wcf的,可是說實話真的忘了…html
因此此次解決完仍是花幾分鐘記錄一下web
WCF服務端:宿主在現有Win服務中,在服務啓動時添加代碼 ,服務代碼就不用寫了,接口和實現按照契約實現便可ide
private ServiceHost serviceHost = null; //服務宿主
//啓動WCF服務 if (serviceHost != null) { serviceHost.Close(); } serviceHost = new ServiceHost(typeof(ControlService)); serviceHost.Open(); Toolkit.Log.Warn("WCF服務啓動");
服務端ServiceModel配置:我的感受也是最麻煩的地方,WCF自己支持多種通訊方式,因此配置較多,不過基本瞭解後也差很少post
詳細可參考:http://www.cnblogs.com/ingstyle/p/5711249.htmlthis
<?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 查看以下圖:url
客戶端WCF服務調用封裝:spa
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; } } } } }
因爲是動態調用的,因此沒有任何配置,能夠向下邊這樣直接使用:code
WSHttpBinding bind = new WSHttpBinding();//重點這兒,能夠傳遞不一樣的Bind,和對應的服務端配置參數(若是參數和服務端不一致則會報錯) WCFHelper.ExecuteMethod<IControlService>(bind,"http://localhost:8000/ServiceModel/service.svc", "ResetTerminal", new object[] { "參數" });
注意第一個參數需根據對應的WCF服務端配置對應xml
例如服務端是webHttpBinding,這兒也換成webHttpBinding bind=new webHttpBinding() 便可,這裏我使用的WSHttpBindinghtm
若是有想了解JQuery調用WCF的方式請參考站長的博客:http://www.cnblogs.com/dudu/archive/2009/07/14/1523082.html
注意:若是碰到 "響應消息的內容類型 text/html; charset=utf-8 與綁定(text/xml; charset=utf-8)的內容類型不匹配。"
也有多是Bind的方式不匹配,另外Host裏的地址儘可能用IP地址來綁定