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 相关文章推荐
xml 与javascript结合的问题解决方法
Mar 24 Javascript
Prototype Number对象 学习
Jul 19 Javascript
html 锁定页面(js遮罩层弹出div效果)
Oct 27 Javascript
JavaScript 设计模式 富有表现力的Javascript(一)
May 26 Javascript
javascript Array 数组常用方法
Apr 05 Javascript
javascript实现连续赋值
Aug 10 Javascript
AngularJS基础 ng-selected 指令简单示例
Aug 03 Javascript
Javascript 正则表达式校验数字的简单实例
Nov 02 Javascript
浅谈$_FILES数组为空的原因
Feb 16 Javascript
Vue中封装input组件的实例详解
Oct 17 Javascript
layui select 禁止点击的实现方法
Sep 05 Javascript
原生js实现表格循环滚动
Nov 24 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中的串行化变量和序列化对象
2006/09/05 PHP
WordPress后台中实现图片上传功能的实例讲解
2016/01/11 PHP
制作个性化的WordPress登陆界面的实例教程
2016/05/21 PHP
thinkPHP框架动态配置用法实例分析
2018/06/14 PHP
PHP匿名函数(闭包函数)详解
2019/03/22 PHP
jQuery LigerUI 使用教程表格篇(1)
2012/01/18 Javascript
jQuery中after()方法用法实例
2014/12/25 Javascript
jQuery中的AjaxSubmit使用讲解
2016/09/25 Javascript
使用ReactJS实现tab页切换、菜单栏切换、手风琴切换和进度条效果
2016/10/17 Javascript
Angular2 多级注入器详解及实例
2016/10/30 Javascript
详解Angular系列之变化检测(Change Detection)
2018/02/26 Javascript
JavaScript中的类型检查
2020/02/03 Javascript
jquery css实现流程进度条
2020/03/26 jQuery
js String.prototype.trim字符去前后空格的扩展
2020/08/23 Javascript
前端性能优化建议
2020/09/17 Javascript
[07:59]2014DOTA2叨叨刀塔 林熊猫称被邀请赛现场盛况震撼
2014/07/21 DOTA
PYTHON正则表达式 re模块使用说明
2011/05/19 Python
python查询sqlite数据表的方法
2015/05/08 Python
Python实现随机漫步功能
2018/07/09 Python
浅谈flask源码之请求过程
2018/07/26 Python
Python + selenium + requests实现12306全自动抢票及验证码破解加自动点击功能
2018/11/23 Python
python实现弹跳小球
2019/05/13 Python
解决pycharm 安装numpy失败的问题
2019/12/05 Python
2020最新pycharm汉化安装(python工程狮亲测有效)
2020/04/26 Python
详解HTML5中ol标签的用法
2015/09/08 HTML / CSS
Etam艾格英国官网:法国著名女装品牌
2019/04/15 全球购物
什么是用户模式(User Mode)与内核模式(Kernel Mode) ?
2014/07/21 面试题
20岁生日感言
2014/01/13 职场文书
交通安全寄语大全
2014/04/08 职场文书
《望庐山瀑布》教学反思
2014/04/22 职场文书
结婚保证书范文
2014/04/29 职场文书
明星邀请函
2015/02/02 职场文书
刑事法律意见书
2015/06/04 职场文书
国富论读书笔记
2015/06/26 职场文书
开学第一周总结
2015/07/16 职场文书
酒店员工管理制度
2015/08/05 职场文书