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 相关文章推荐
js调用flash的效果代码
Apr 26 Javascript
js实现在文本框光标处添加字符的方法介绍
Nov 24 Javascript
js实现表单Radio切换效果的方法
Aug 17 Javascript
jQuery实现仿QQ在线客服效果的滚动层代码
Oct 15 Javascript
AngularJS入门教程之Scope(作用域)
Jul 27 Javascript
jQuery延迟执行的实现方法
Dec 21 Javascript
js处理层级数据结构的方法小结
Jan 17 Javascript
js实现炫酷的左右轮播图
Jan 18 Javascript
原生js开发的日历插件
Feb 04 Javascript
基于JQuery及AJAX实现名人名言随机生成器
Feb 10 Javascript
分享十三个最佳JavaScript数据网格库
Apr 07 Javascript
微信小程序项目总结之记账小程序功能的实现(包括后端)
Aug 20 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 网页游戏开发入门教程一(webgame+design)
2009/10/26 PHP
遍历指定目录下的所有目录和文件的php代码
2011/11/27 PHP
PHP判断用户是否已经登录(跳转到不同页面或者执行不同动作)
2016/09/22 PHP
PHP 验证身份证是否合法的函数
2017/02/09 PHP
Laravel如何使用数据库事务及捕获事务失败后的异常详解
2017/10/23 PHP
php+mysql开发的最简单在线题库(在线做题系统)完整案例
2019/03/30 PHP
JS阻止冒泡事件以及默认事件发生的简单方法
2014/01/17 Javascript
Vuejs第十二篇之动态组件全面解析
2016/09/09 Javascript
JS表单验证方法实例小结【电话、身份证号、Email、中文、特殊字符、身份证号等】
2017/02/14 Javascript
js获取浏览器的各种属性
2017/04/27 Javascript
win系统下nodejs环境安装配置
2017/05/04 NodeJs
微信小程序自定义组件
2017/08/16 Javascript
详解IWinter 一个路由转控制器的 Nodejs 库
2017/11/15 NodeJs
vue实现word,pdf文件的导出功能
2018/07/31 Javascript
使用Vue开发自己的Chrome扩展程序过程详解
2019/06/21 Javascript
Python实现堆排序的方法详解
2016/05/03 Python
python opencv之SURF算法示例
2018/02/24 Python
python游戏地图最短路径求解
2019/01/16 Python
python pip源配置,pip配置文件存放位置的方法
2019/07/12 Python
Django MEDIA的配置及用法详解
2019/07/25 Python
给Python学习者的文件读写指南(含基础与进阶)
2020/01/29 Python
TensorFlow2.X使用图片制作简单的数据集训练模型
2020/04/08 Python
python由已知数组快速生成新数组的方法
2020/04/08 Python
浅谈pycharm导入pandas包遇到的问题及解决
2020/06/01 Python
使用SimpleITK读取和保存NIfTI/DICOM文件实例
2020/07/01 Python
python全栈开发语法总结
2020/11/22 Python
解决TensorFlow训练模型及保存数量限制的问题
2021/03/03 Python
潘多拉意大利官方网上商城:网上选购PANDORA珠宝
2018/10/07 全球购物
应用心理学专业求职信
2014/08/04 职场文书
大三学生英语考试作弊检讨书
2015/01/01 职场文书
工作保证书怎么写
2015/02/28 职场文书
2015年出纳年终工作总结
2015/05/14 职场文书
第一军规观后感
2015/06/12 职场文书
新娘婚礼致辞
2015/07/27 职场文书
公司转让协议书
2016/03/19 职场文书
经典《舰娘》游改全新动画预告 预定11月开播
2022/04/01 日漫