WCF大家一般都知道,至于和webservice的区别,大家百度就好,最近手头新项目想用一下WCF,于是便花时间写了个简单的WCF AJAX DEMO,仅是DEMO,主要是JSON解析这块,WCF这一块没什么好说的,就是VS直接生成的。PS:JSON解析一块借鉴了一些代码,经过了自己的修修改改。
开发环境:
操作系统:WIN7 64 旗舰
服务器:IIS7
IDE:VS2010
开发语言:C#
1.WCF服务器端编码,其实很简单,VS—右击需要添加WCF文件的文件夹或项目—新建项—在Web项下选择“启用了AJAX的WCF服务”,OK文件生成
代码形如(测试用):
[ServiceContract(Namespace = "WCFTest2")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WCFTest2 { // 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json) // 要创建返回 XML 的操作, // 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)], // 并在操作正文中包括以下行: // WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; [OperationContract] public void DoWork() { // 在此处添加操作实现 return; } [OperationContract] public int test2(int aa,int bb) { return aa + bb; } [OperationContract] public List<BaseModel> test3(List<BaseModel> aa) { return aa; }}
注意,如果要在WCF中使用session,请注意以下几点:
1. web.config中设置<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />
2.服务代码端每个service类前应设置特性为 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.required)]
3.当然你得设置浏览器允许cookie
4.这时你就可以再service端用session啦,引入System.Web,然后以HttpContext.Current.Session[key] ="Some value" ; 的方式访问
另外:简单需求下web.config文件基本可以不要动,有其他具体需要可以百度……
2. JS端ajax编码
以下是解析JSON 和ajax 的代码
var ajaxLoc = "http://localhost:80"; //过滤WCF返回的json结果 function JsonResultFilter(result) { if (result.d && result.d.length > 0) { for (var i = 0; i < result.d.length; i++) { var rs = result.d[i]; if (rs.__type) { JsonFilter(rs); DateHandler(rs); } } } return result.d; } function JsonFilter(node) { if (node && node.__type) { delete node.__type; } else { return; } for (var item in node) { JsonFilter(node[item]); } } function DateJsonResultHandler(result) { if (result && result.length > 0) { for (var i = 0; i < result.length; i++) { DateHandler(result[i]); } } } //过滤WCF传回的dateTime类型 function DateHandler(node) { if (!node) { return; } for (var item in node) { if (node[item]) { node[item] = $.wcfDate2JsDateString(node[item]); } } } //格式化时间 function TimeFomat(date) { if (!date.getFullYear()) { return ''; } var tf = function (time) { if (time.toString(10).length == 1) { return '0' + time.toString(); } return time; }; return tf(date.getFullYear()) + '-' + tf(date.getMonth() + 1) + '-' + tf(date.getDate()) + ' ' + tf(date.getHours()) + ':' + tf(date.getMinutes()) + ':' + tf(date.getSeconds()); } //简单封装jquery ajax请求 function majax(url1,data1,success1,error1) { $.ajax({ url: ajaxLoc + url1,type: "POST",contentType: "text/json",data: data1,dataType: "json",success: function (returnValue) { var rs = JsonResultFilter(returnValue); success1(rs); },error: error1 }); } //将Object对象转换成格式为json的字符串,支持子对象,一般应用于有且只能有一个实体参数的接口 //参数: //o:object对象 //paramName:传入到后台方法的参数名 //如: //var paramList = {}; //var obj = {}; //obj.CreateDate = $.jsDate2WcfDate("2010-1-2"); //obj.CreateBy = "11"; //obj.ModifyBy = "zz1"; //obj.test = {}; //obj.test.zz = "11"; //paramList[0] = obj; //var str = obj2jsonStr(paramList,"aa"); //则str为:{ "aa": [{"CreateDate":"/Date(1262361600000+0000)/","CreateBy": "11","ModifyBy": "zz1","test": { "zz": "11"} } ] } function obj2jsonStrList(o,paramName) { var r = obj2jsonStr(o); r = r.toString().replace("{{","[{"); var len = r.toString().length; var arr = r.toString().split(''); arr[len - 1] = ']'; var rb = arr.join(''); rb = '{"' + paramName + '": ' + rb + '}'; return rb; } //将Object对象转换成格式为json的字符串,一般应用于非实体参数的接口 //参数: //o:object对象 //如: //var obj = {}; //obj.aa = "11"; //obj.bb = "22"; //var str = obj2jsonStr(obj); //则str为:{"aa":"11","bb":"22"} function obj2jsonStr(o) { var r = []; if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n") .replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t") + "\""; if (typeof o == "object") { if (!o.sort) { for (var i in o) { if (isNaN(i.toString())) { r.push("\"" + i + "\"" + ":" + obj2jsonStr(o[i])); //(i + ":" + obj2jsonStr(o[i])); } else { r.push(obj2jsonStr(o[i])); } } if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/ .test(o.toString)) { r.push("toString:" + o.toString.toString()); } r = "{" + r.join() + "}" } else { for (var i = 0; i < o.length; i++) r.push(obj2jsonStr(o[i])) r = "[" + r.join() + "]" } return r; } return o.toString(); } //jQuery扩展,使WCF兼容c# DateTime类型 jQuery.extend( { wcfDate2JsDateString: function (wcfDate) { if (wcfDate && wcfDate.toString().substring(0,5) == '/Date') { var date = new Date(parseInt(wcfDate.substring(6))); return TimeFomat(date); } return wcfDate; },jsDate2WcfDate: function (jsDate) { var ttmp = jsDate.split(' '); var dt; var ti = "00:00:00"; var str = ""; ; if (ttmp.length > 0) { dt = ttmp[0]; var d = dt.split('-'); if (d.length != 3) { alert('请输入正确的日期格式,如:2010-01-01'); return; } //形如:2010/01/01,这样才能在IE低版本中生成正确的Date对象。 str += d[1].toString() + "/" + d[2] + "/" + d[0] + " "; } if (ttmp.length > 1) { ti = ttmp[1]; } str += ti; var date = new Date(str); return "\/Date(" + date.getTime() + "+0000)\/"; } } );3.页面调用,注:我引入的jquery是1.7.2版本,这个版本基本上可以满足各种层次的开发需求,并且对于IE低版本的兼容性也不错(大家都知道jquery 1.8和之后的版本放弃了对IE678的支持)
<script type="text/javascript">原文链接:https://www.f2er.com/ajax/165090.html$(document).ready(function () { $("#login").click(function () { lo(); }); }); function lo() { // var obj = {}; // obj.ui = $("#ui").val(); // obj.cc = "cc"; // var str = obj2jsonStr(obj); var paramList = {}; var obj = {}; obj.CreateDate = $.jsDate2WcfDate("2010-1-2"); obj.CreateBy = "呵呵"; obj.ModifyBy = "zz1"; obj.test = {}; obj.test.zz = "11"; paramList[0] = obj; var str = obj2jsonStrList(paramList,"aa"); majax('/ServiceAPI/WCFTest2.svc/test3',str,//'{ "aa": [{"CreateDate":"' + $.jsDate2WcfDate("2010-1-2") + '","test": { "zz": "11"} } ] }',//,{"CreateDate":"' + $.jsDate2WcfDate("2010-1-2 12:00:00") + '","CreateBy": "12","ModifyBy": "zz2","test": { "zz": "12"}} function (returnValue) { alert(returnValue[0].CreateBy); //alert(rs); zz = 0; //window.location = "/testWeb1.aspx"; },function (XMLHttpRequest,textStatus,errorThrown) { switch (XMLHttpRequest.status) { case 404: alert("找不到相关服务"); break; case 500: default: alert(""); } }); } </script>