源码如下:
[ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(Method = "*", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] CompositeType GetDataUsingDataContract(CompositeType composite); } [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 : IService1 { public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) { throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; } }
通过如下POST方法,是可以正常调用WCF服务方法的
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="jquery-1.4.4.min.js" type="text/javascript"></script> </head> <body> <input id="Text1" type="text" /><input id="Button1" type="button" value="button" /> <fieldset> <legend>结果输出:</legend> <div id="resultbox"> </div> </fieldset> <script type="text/javascript"> $(function () { $("#Button1").click(function () { alert("click!"); $.ajax({ url: "Service1.svc/GetDataUsingDataContract", contentType:"text/json", type: "post", datatype: "json", data:{ composite: { BoolValue: true, StringValue: $("#Text1").val()} }, success: function (r,s,x) { $("#resultbox").append("<p>" + JSON.stringify(r) + "</p>"); } }); }); }); </script> </body> </html>
但若将type改为get,则报如下错误:
约定“IService1”中的操作“GetDataUsingDataContract”具有名称为“composite”、类型为“WcfService1.CompositeType”的查询变量,但“QueryStringConverter”不能转换类型“WcfService1.CompositeType”。UriTemplate 查询值的变量必须为“QueryStringConverter”可转换的类型。
还请高手指教,非常感谢!
WebInvoke改为WebGet试试
一样的
UriTemplate = "/?composite={composite}"