在网上查找了很多资料,90%的资料中都是在web项目中添加.SVC文件来进行的,也就是使用IIS托管的服务,
而且相关资料中也未说的很详细,GET方法很快就调通了,POST方式却倒腾了很久,
最后发现在很多资料中提及的脚本调用必须添加的
<behavior name="webJSBehavior">
<!--这里必须设置,允许脚本调用-->
<enableWebScript /></behavior>
根本上会阻碍POST方式的成功,花了几天的时间才得以最终将这个Demo完成。
1.WCF服务
配置WCF服务
1.1Contract契约,其中黄色背景字部分比较重要,
namespace MyServices { [ServiceContract(Namespace = "www.yycode.net", Name = "MyTestService")] public interface IMyTestService { [OperationContract] string GetData(int value); [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string HelloWorld(); [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string GetCount(); [OperationContract]
//这里的AddOrder方法一会会使用POST方式调用,配置会稍微不同。 [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)] string AddOrder(string OrderID); } }
1.2服务
namespace MyServices { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。 [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] public class MyTestService : IMyTestService { public static int CountGet = 0; public string GetData(int value) { CountGet += 1; return string.Format("You entered: {0}", value); } public string HelloWorld() { CountGet += 1; return string.Format("HelloWorld {0}",DateTime.Now); } public string AddOrder(string OrderID) { return string.Format("成功新增订单{0}",OrderID); } public string GetCount() { return string.Format("成功被调用{0}次",CountGet); } public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) { throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; } } }
代码“[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]”中的"jsoncallback"可以为其他任何字符串,在于调用服务时标识传入的参数
1.3配置终结点App.Config,其中黄色背景里面的内容值得特别注意。
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true"/> </system.web> <!-- 部署服务库项目时,必须将配置文件的内容添加到 主机的 app.config 文件中。System.Configuration 不支持库的配置文件。 --> <system.serviceModel> <services> <service behaviorConfiguration="MyServices.Service1Behavior" name="MyServices.MyTestService"> <endpoint address="norml" binding="basicHttpBinding" contract="MyServices.IMyTestService"> <identity> <dns value="localhost"/> </identity> </endpoint> <!--http://127.0.0.1:9901/MyTestService/--> <endpoint address="Jweb" binding="webHttpBinding" behaviorConfiguration="webhttpBehavior" bindingConfiguration="webBinding" contract="MyServices.IMyTestService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://127.0.0.1:90/MyServices/MyTestService/"/> </baseAddresses> </host> </service> </services> <behaviors> <endpointBehaviors> <behavior name="webJSBehavior"> <enableWebScript /> </behavior> <behavior name="webhttpBehavior"> <webHttp/> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="MyServices.Service1Behavior"> <!-- 为避免泄漏元数据信息, 请在部署前将以下值设置为 false --> <serviceMetadata httpGetEnabled="True"/> <!-- 要接收故障异常详细信息以进行调试, 请将以下值设置为 true。在部署前 设置为 false 可避免泄漏异常信息 --> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> </behaviors> <bindings> <webHttpBinding> <!--crossDomainScriptAccessEnabled指定脚本可以跨域访问--> <binding name="webBinding" crossDomainScriptAccessEnabled="true"/> </webHttpBinding> </bindings> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"> <baseAddressPrefixFilters> <add prefix="string"/> </baseAddressPrefixFilters> </serviceHostingEnvironment> </system.serviceModel> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> </startup> </configuration>
Winform托管WCF服务
新建winform项目,在项目中引用WCF服务类库,下面是Winform相关主要代码,
如何在WinForm中托管WCF服务的方式可以参考:WCF的几种寄宿方式
View Code
void worker_DoWork(object sender, DoWorkEventArgs e) { try { serviceHost = new ServiceHost(typeof(MyTestService)); if (serviceHost.State != CommunicationState.Opened) { serviceHost.Open(); } e.Result = "正常"; } catch (Exception ex) { e.Result = ex.Message; } }
WEB端调用WCF服务
基于JQuery写的JS文件,里面包含一个Format函数,还有二次包装GET和POST方法
var ServiceUrl = "http://127.0.0.1:9090/MyServices/MyTestService/Jweb/{0}?jsoncallback=?"; $.format = function (source, params) { if (arguments.length == 1) return function () { var args = $.makeArray(arguments); args.unshift(source); return $.format.apply(this, args); }; if (arguments.length > 2 && params.constructor != Array) { params = $.makeArray(arguments).slice(1); } if (params.constructor != Array) { params = [params]; } $.each(params, function (i, n) { source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n); }); return source; }; $.GetWCF = function (Method,CallBack) { var url1 =$.format(ServiceUrl,Method); $.ajax({ type: "GET", dataType: "json", url: url1, async:false, success: function (data, status) { CallBack(data, status); }, error: function (str, txtStatus, mes) { alert(txtStatus + mes); } }); } //OrderID $.PostWCF = function (Method,DataContent,CallBack) { var url1 = $.format(ServiceUrl, Method); $.ajax({ type: "POST",//Post方式 data: DataContent, dataType: "json", contentType: 'application/json; charset=utf-8', async: false,//非异步 url: url1, success: function (data, status) { CallBack(data, status); }, error: function (str, txtStatus, mes) { alert(txtStatus+mes); //alert(mes); } }); }
页面代码
View Code
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script> <script src="Scripts/MyJquery.js"></script> <script type="text/javascript"> function AlertResult(data, status) { alert("数据:" + data + "\n状态:" + status); } function AddMessage(data, status) { var mess=$("#Message"); mess.html($.format("{0}</br>数据:{1}状态:{2}", mess.html(), data, status)); } function AddOrderResult(data, status) { var mess = $("#Message"); mess.html($.format("{0}</br>数据:{1}状态:{2}", mess.html(), data.AddOrderResult, status)); } $(document).ready(function () { $("#Button1").click(function () { $.GetWCF("HelloWorld", AddMessage); $.GetWCF("GetCount", AddMessage); $.PostWCF("AddOrder",{ "OrderID": "19851221"}, AddOrderResult); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <div id="Message" style="height:100px;"> </div> <div> <input id="Button1" type="button" value="调用AJAX" /> <br /> <br /> <br /> </div> </div> </form> </body> </html>
技术交流请加群517867216 入群验证请带上程序员的特点。