本文共 4477 字,大约阅读时间需要 14 分钟。
1、能被ajax get
2、能post
3、wcf正常调用
实现:
1 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 2 [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] 3 public class WCFJsonTest : IWCFJsonTest 4 { 5 6 public ListGetTest(string id) 7 { 8 List list = new List (); 9 TestModel t = new TestModel();10 t.Ids = 1;11 t.Names = id;12 list.Add(t);13 14 TestModel t1 = new TestModel();15 t1.Ids = 1;16 t1.Names = id+"_"+Guid.NewGuid().ToString();17 list.Add(t1);18 19 return list;20 }21 22 23 public TestModel PostTest(string id, string name)24 {25 TestModel t1 = new TestModel();26 t1.Ids = int.Parse(id);27 t1.Names = name + "_" + Guid.NewGuid().ToString();28 return t1;29 }30 31 32 public TestModel PostTest1(TestModel model)33 {34 TestModel t1 = new TestModel();35 t1.Ids = model.Ids;36 t1.Names = model.Names + "_" + Guid.NewGuid().ToString();37 return t1;38 }39 }
接口:
1 [ServiceContract] 2 3 public interface IWCFJsonTest 4 { 5 [OperationContract] 6 [WebGet(UriTemplate = "/GetTest/{id}", ResponseFormat = WebMessageFormat.Json)] 7 ListGetTest(string id); 8 9 [OperationContract]10 [WebInvoke(Method="GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]11 TestModel PostTest(string id, string name);12 13 [OperationContract]14 [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]15 TestModel PostTest1(TestModel model);16 }
配置:
endpoint配置两个一个web使用webHttpBinding,一个给wcf
12 3 4 10 115 96 7 8 12 2813 2214 1715 16 18 2119 20 23 2724 2625 29 4930 3231 33 4839 4741 42 4644 45 50 5451 5352
调用:
wcf正常调用地址:http://xxxxxx:xxxx/JsonTestService.svc
post:http://xxxxxx:xxxx/JsonTestService.svc/PostTest
get:http://xxxxxx:xxxx/JsonTestService.svc/GetTest/2
例如:
1 string srcString=GetData("", "http://xxxxxx:xxxx/JsonTestService.svc/GetTest/2"); 2 3 srcString = PostHelper.GetPermissionRemoteData("http://xxxxxx:xxxx/JsonTestService.svc/PostTest","{\"id\":\"10\",\"name\":\"张三\"}","text/json"); 4 5 string jsonStr = "{\"Ids\":\"10\",\"Names\":\"张三1\"}"; 6 srcString = PostHelper.GetPermissionRemoteData("http://xxxxxx:xxxx/JsonTestService.svc/PostTest1", "{\"model\": "+ jsonStr+" }", "text/json"); 7 8 WCFJsonTestClient client = new WCFJsonTestClient(); 9 var r = client.GetTest("1");10 var r1 = client.PostTest("1", "a");11 var r2 = client.PostTest1(new TestModel() { Ids = 1, Names = "2" });
1 $.ajax({ 2 type: "GET", 3 dataType: "jsonp", 4 url: 'http://xxxxxx:xxxx/JsonTestService.svc/GetTest/2', 5 success: function (data) { 6 console.log(data); 7 }, 8 error: function (XMLHttpRequest, textStatus, errorThrown) { 9 console.log('err1' + XMLHttpRequest);10 console.log('err2' + textStatus);11 console.log('err3' + errorThrown);12 }13 });
转载地址:http://sxhca.baihongyu.com/