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 相关文章推荐
单元选择合并变色示例代码
May 26 Javascript
详解Bootstrap glyphicons字体图标
Jan 04 Javascript
jquery及js实现动态加载js文件的方法
Jan 21 Javascript
JavaScript 栈的详解及实例代码
Jan 22 Javascript
浅谈手写node可读流之流动模式
Jun 01 Javascript
vue中的适配px2rem示例代码
Nov 19 Javascript
微信小程序学习笔记之登录API与获取用户信息操作图文详解
Mar 29 Javascript
layui 图片上传+表单提交+ Spring MVC的实例
Sep 21 Javascript
微信小程序日历插件代码实例
Dec 04 Javascript
vue 实现动态路由的方法
Jul 06 Javascript
vue路由结构可设一层方便动态添加路由操作
Aug 31 Javascript
Javascript的promise,async和await的区别详解
Mar 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中最容易忘记的一些知识点总结
2013/04/28 PHP
如何取得中文字符串中出现次数最多的子串
2013/08/08 PHP
PHP中feof()函数实例测试
2014/08/23 PHP
PHP日期函数date格式化UNIX时间的方法
2015/03/19 PHP
php经典算法集锦
2015/11/14 PHP
PHP addAttribute()函数讲解
2019/02/03 PHP
laravel dingo API返回自定义错误信息的实例
2019/09/29 PHP
Javascript Tab 导航插件 (23个)
2009/06/11 Javascript
解读JavaScript代码 var ie = !-[1,] 最短的IE判定代码
2011/05/28 Javascript
js实现仿QQ秀换装效果的方法
2015/03/04 Javascript
jQuery.Highcharts.js绘制柱状图饼状图曲线图
2015/03/14 Javascript
js+canvas简单绘制圆圈的方法
2016/01/28 Javascript
Bootstrap基本样式学习笔记之表单(3)
2016/12/07 Javascript
浅析JavaScript的几种Math函数,random(),ceil(),round(),floor()
2016/12/22 Javascript
nodejs中art-template模板语法的引入及冲突解决方案
2017/11/07 NodeJs
解决vue A对象赋值给B对象,修改B属性会影响到A的问题
2018/09/25 Javascript
微信小程序如何使用globalData的方法
2019/06/06 Javascript
微信小程序之滑动页面隐藏和显示组件功能的实现代码
2020/06/19 Javascript
解决vue props传Array/Object类型值,子组件报错的情况
2020/11/07 Javascript
[02:34]DOTA2英雄基础教程 幽鬼
2014/01/02 DOTA
[02:13] 完美世界DOTA2联赛PWL DAY5集锦
2020/11/03 DOTA
浅谈python socket函数中,send与sendall的区别与使用方法
2017/05/09 Python
Jupyter中直接显示Matplotlib的图形方法
2018/05/24 Python
在django中自定义字段Field详解
2019/12/03 Python
基于Python3读写INI配置文件过程解析
2020/07/23 Python
python使用Word2Vec进行情感分析解析
2020/07/31 Python
深入浅析Python代码规范性检测
2020/07/31 Python
python 对一幅灰度图像进行直方图均衡化
2020/10/27 Python
利用Python过滤相似文本的简单方法示例
2021/02/03 Python
纯CSS实现菜单、导航栏的3D翻转动画效果
2014/04/23 HTML / CSS
英国著名的药妆网站:Escentual
2016/07/29 全球购物
澳大利亚在线批发商:Simply Wholesale
2021/02/24 全球购物
委托书格式要求
2015/01/28 职场文书
北京导游词
2015/02/12 职场文书
2016年小学中秋节活动总结
2016/04/05 职场文书
MySQL串行化隔离级别(间隙锁实现)
2022/06/16 MySQL