jQuery调用RESTful WCF示例代码(GET方法/POST方法)


Posted in Javascript onJanuary 26, 2014

不废话了,直奔主题吧

wcf端:

近几年比较流行restful,为了能让ajax调用,同时也为了支持restful风格的uri,在创建一个Ajax-enabled Wcf Service后,必须手动修改svc文件,指定Factory,即:

<%@ ServiceHost Language="C#" Debug="true" Service="ajaxSample.HelloWorld" CodeBehind="HelloWorld.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

注:如果不添加Factory,则wcf将无法用类似http://localhost/helloWorld.svc/Hello/person/name 的restful方式直接访问。

同时还要去掉web.config中的<enableWebScript />即类似:

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ajaxSample.HelloWorldAspNetAjaxBehavior">
          <!--<enableWebScript />-->
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service name="ajaxSample.HelloWorld">
        <endpoint address="" behaviorConfiguration="ajaxSample.HelloWorldAspNetAjaxBehavior"
          binding="webHttpBinding" contract="ajaxSample.HelloWorld" />
      </service>
    </services>
  </system.serviceModel>

好了,开始写代码,鉴于wcf调用时有GET/POST二种方式,下面把几种常用的情况都写一个示例方法:

using System.Collections.Generic; 
using System.ServiceModel; 
using System.ServiceModel.Activation; 
using System.ServiceModel.Web; namespace ajaxSample 
{ 
    [ServiceContract(Namespace = "http://yjmyzz.cnblogs.com/")] 
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
    public class HelloWorld 
    { 
        /// <summary> 
        /// 只能Post的Restful方法 
        /// </summary> 
        /// <param name="person"></param> 
        /// <param name="welcome"></param> 
        /// <returns></returns> 
        [OperationContract] 
        [WebInvoke(Method = "POST", UriTemplate = "PostRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)] 
        public List<string> PostRestfulTest(string person,string welcome) 
        { 
            List<string> result = new List<string>(); 
            result.Add("PostRestfulTest -> from server:"); 
            result.Add(person); 
            result.Add(welcome); 
            return result; 
        } 
        /// <summary> 
        /// 只能Get的Restful方法 
        /// </summary> 
        /// <param name="person"></param> 
        /// <param name="welcome"></param> 
        /// <returns></returns> 
        [OperationContract] 
        [WebInvoke(Method = "GET", UriTemplate = "GETRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)] 
        public List<string> GETRestfulTest(string person, string welcome) 
        { 
            List<string> result = new List<string>(); 
            result.Add("GETRestfulTest -> from server:"); 
            result.Add(person); 
            result.Add(welcome); 
            return result; 
        } 
        /// <summary> 
        /// 即可Get与Post的Restful方法 
        /// </summary> 
        /// <param name="person"></param> 
        /// <param name="welcome"></param> 
        /// <returns></returns> 
        [OperationContract] 
        [WebInvoke(Method = "*", UriTemplate = "RestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)] 
        public List<string> RestfulTest(string person, string welcome) 
        { 
            List<string> result = new List<string>(); 
            result.Add("RestfulTest -> from server:"); 
            result.Add(person); 
            result.Add(welcome); 
            return result; 
        } 
  
        /// <summary> 
        /// 只能Post的常规方法(注:Post方式,BodyStyle必须设置成WrappedRequest或Wrapped) 
        /// </summary> 
        /// <param name="person"></param> 
        /// <param name="welcome"></param> 
        /// <returns></returns> 
        [OperationContract] 
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.WrappedRequest)] 
        public List<string> PostTest(string person, string welcome) 
        { 
            List<string> result = new List<string>(); 
            result.Add("PostRestfulTest -> from server:"); 
            result.Add(person); 
            result.Add(welcome); 
            return result; 
        } 
        /// <summary> 
        /// 只能Get的常规方法 
        /// </summary> 
        /// <param name="person"></param> 
        /// <param name="welcome"></param> 
        /// <returns></returns> 
        [OperationContract] 
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)] 
        public List<string> GETTest(string person, string welcome) 
        { 
            List<string> result = new List<string>(); 
            result.Add("GETTest -> from server:"); 
            result.Add(person); 
            result.Add(welcome); 
            return result; 
        } 
          
          
    } 
}

jQuery调用代码:
<script type="text/javascript"> 
    $().ready(function () {  
        $.post("HelloWorld.svc/PostRestfulTest/111/222", function (data) { 
            alert("PostRestfulTest调用成功,返回值为:" + data); 
        }) 
        $.get("HelloWorld.svc/GETRestfulTest/333/444", function (data) { 
            alert("GETRestfulTest调用成功,返回值为:" + data); 
        }) 
        $.get("HelloWorld.svc/RestfulTest/555/666", function (data) { 
            alert("RestfulTest GET方式调用成功,返回值为:" + data); 
        }) 
 
        $.post("HelloWorld.svc/RestfulTest/777/888", function (data) { 
            alert("RestfulTest POST方式调用成功,返回值为:" + data); 
        }) 
 
        $.get("HelloWorld.svc/GETTest", { person: "aaa", welcome: "bbb" }, function (data) { 
            alert("GETTest 调用成功,返回值为:" + data); 
        }); 
 
        $.ajax({ 
            url: "HelloWorld.svc/PostTest", 
            type: "POST", 
            contentType: "application/json", 
            data: '{"person":"ccc","welcome":"ddd"}', 
            dataType: "html", 
            success: function (data) { alert("PostTest调用成功,返回值为:" + data); } 
        }); 
    }) 
</script>

有时候,WCF暴露的方法中可能需要一些敏感信息做为参数(比如用户名/用户ID之类),这时如果直接用js来调用wcf,可能会把这部分信息泄漏在客户端,这种场景下,我们也经常用一个服务端的ashx来做中转

TestService.svc

using System.ServiceModel; namespace ashx_jQuery 
{ 
     [ServiceContract] 
    public class TestService  
    { 
         /// <summary> 
         /// 获取当前用户指定月份的工资 
         /// </summary> 
         /// <param name="userId"></param> 
         /// <param name="month"></param> 
         /// <returns></returns> 
         [OperationContract] 
        public double GetSalary(int userId,int month) 
        { 
            if (month == 1)//只是演示而已 
            { 
                return 5000; 
            } 
            else 
            { 
                return 1000; 
            } 
        } 
    } 
}

AjaxProcess.ashx
using System.Web; namespace ashx_jQuery 
{ 
    /// <summary> 
    /// Summary description for AjaxProcess 
    /// </summary> 
    public class AjaxProcess : IHttpHandler 
    { 
        public void ProcessRequest(HttpContext context) 
        { 
            context.Response.ContentType = "text/plain"; 
            string month = context.Request["month"]; 
            TestService wcf = new TestService(); 
            double salary = wcf.GetSalary(GetUserId(), int.Parse(month)); 
            context.Response.Write("{salary:" + salary + "}"); 
        } 
  
        /// <summary> 
        /// 获取当前的用户ID 
        /// </summary> 
        /// <returns></returns> 
        private int GetUserId()  
        { 
            return 1; 
        } 
        public bool IsReusable 
        { 
            get
            { 
                return false; 
            } 
        } 
    } 
}

jQuery调用:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="ashx_jQuery._default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>jQuery ashx Sample</title> 
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script> 
    <script type="text/javascript"> 
        $().ready(function () { 
            $("#btnTest").click(function () { 
                $.post( 
                    "AjaxProcess.ashx", 
                    { month:1 }, 
                    function (e) { 
                        var d = eval("(" + e + ")"); 
                        alert(d.salary); 
                    }, "html"); 
            }) 
        }) 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <input type="button" value="GetSalary" id="btnTest"/> 
    </form> 
</body> 
</html>

示例代码:点击下载 
Javascript 相关文章推荐
运用jquery实现table单双行不同显示并能单行选中
Jul 25 Javascript
解决jQuery插件tipswindown与hintbox冲突
Nov 05 Javascript
javascript对JSON数据排序的3个例子
Apr 12 Javascript
Redis基本知识、安装、部署、配置笔记
Mar 05 Javascript
易操作的jQuery表单提示插件
Dec 01 Javascript
javascript学习指南之回调问题
Apr 23 Javascript
socket.io学习教程之基础介绍(一)
Apr 29 Javascript
详解使用element-ui table组件的筛选功能的一个小坑
Nov 02 Javascript
JS实现的简单tab切换功能完整示例
Jun 20 Javascript
Vue数据双向绑定原理实例解析
May 15 Javascript
如何在 ant 的table中实现图片的渲染操作
Oct 28 Javascript
微信小程序 WeUI扩展组件库的入门教程
Apr 21 Javascript
javascript:json数据的页面绑定示例代码
Jan 26 #Javascript
jQuery focus和blur事件的应用详解
Jan 26 #Javascript
当jQuery1.7遇上focus方法的问题
Jan 26 #Javascript
jQuery中delegate和on的用法与区别详细解析
Jan 26 #Javascript
使用javascript为网页增加夜间模式
Jan 26 #Javascript
jQuery:delegate中select()不起作用的解决方法(实例讲解)
Jan 26 #Javascript
javascript:FF/Chrome与IE动态加载元素的区别说明
Jan 26 #Javascript
You might like
PHP中使用cURL实现Get和Post请求的方法
2013/03/13 PHP
浅析Apache中RewriteCond规则参数的详细介绍
2013/06/30 PHP
php读取3389的脚本
2014/05/06 PHP
php出现内存位置访问无效错误问题解决方法
2014/08/16 PHP
PHP中应该避免使用同名变量(拆分临时变量)
2015/04/03 PHP
JavaScript 封装Ajax传递的数据代码
2009/06/05 Javascript
JS下载文件|无刷新下载文件示例代码
2014/04/17 Javascript
Internet Explorer 11 浏览器介绍:别叫我IE
2014/09/28 Javascript
分享20个提升网站界面体验的jQuery插件
2014/12/15 Javascript
js计算德州扑克牌面值的方法
2015/03/04 Javascript
JS+CSS实现大气清新的滑动菜单效果代码
2015/10/22 Javascript
快速解决js中window.location.href不工作的问题
2016/11/02 Javascript
总结javascript三元运算符知识点
2018/09/28 Javascript
使用javascript做时间倒数读秒功能的实例
2019/01/23 Javascript
nodejs实现聊天机器人功能
2019/09/19 NodeJs
Python编程给numpy矩阵添加一列方法示例
2017/12/04 Python
小米5s微信跳一跳小程序python源码
2018/01/08 Python
在python下使用tensorflow判断是否存在文件夹的实例
2019/06/10 Python
python实现DEM数据的阴影生成的方法
2019/07/23 Python
python实现各种插值法(数值分析)
2019/07/30 Python
python BlockingScheduler定时任务及其他方式的实现
2019/09/19 Python
Win10下python 2.7与python 3.7双环境安装教程图解
2019/10/12 Python
python 监测内存和cpu的使用率实例
2019/11/28 Python
在OpenCV里实现条码区域识别的方法示例
2019/12/04 Python
python 利用zmail库发送邮件
2020/09/11 Python
canvas绘图按照contain或者cover方式适配并居中显示
2019/02/18 HTML / CSS
Bootstrap File Input文件上传组件
2020/12/01 HTML / CSS
英国最大的宝石首饰超市:QP Jewellers
2018/09/23 全球购物
意大利灯具购物网站:Lampade.it
2018/10/18 全球购物
飞利浦法国官网:Philips法国
2019/07/10 全球购物
自动化专业个人求职信范文
2013/11/29 职场文书
亚运会口号
2014/06/20 职场文书
竞聘演讲稿开场白
2014/08/25 职场文书
放射科岗位职责
2015/02/14 职场文书
2015年秋季学校开学标语
2015/07/16 职场文书
Python 中的单分派泛函数你真的了解吗
2021/06/22 Python