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 DOM 操作实现代码
Aug 01 Javascript
javascript中callee与caller的区别分析
Apr 20 Javascript
理解javascript闭包
Dec 15 Javascript
js获取所有checkbox的值的简单实例
May 30 Javascript
jQuery文本框得到与失去焦点动态改变样式效果
Sep 08 Javascript
微信小程序侧边栏滑动特效(左右滑动)
Jan 23 Javascript
JS实现复选框的全选和批量删除功能
Apr 05 Javascript
前端主流框架vue学习笔记第一篇
Jul 26 Javascript
javascript标准库(js的标准内置对象)总结
May 26 Javascript
微信小程序实现图片上传
May 23 Javascript
JS使用正则表达式提交页面验证的代码
Oct 16 Javascript
JQuery事件委托(适用于给动态生成的脚本元素添加事件)
Feb 01 jQuery
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+MySQL 手工注入语句大全 推荐
2009/10/30 PHP
浅析虚拟主机服务器php fsockopen函数被禁用的解决办法
2013/08/07 PHP
Smarty中调用FCKeditor的方法
2014/10/27 PHP
php实现字符串首字母大写和单词首字母大写的方法
2015/03/14 PHP
PHP+MYSQL中文乱码问题
2015/07/01 PHP
幻宇的层模拟窗口效果-提供演示和下载
2007/01/20 Javascript
JS的递增/递减运算符和带操作的赋值运算符的等价式
2007/12/08 Javascript
自己开发Dojo的建议框架
2008/09/24 Javascript
Javascript下判断是否为闰年的Datetime包
2010/10/26 Javascript
基于jQuery的动态增删改查表格信息,可左键/右键提示(原创自Zjmainstay)
2012/07/31 Javascript
jQuery获取和设置表单元素的方法
2014/02/14 Javascript
JavaScript控制各种浏览器全屏模式的方法、属性和事件介绍
2014/04/03 Javascript
jquery中 $.expr使用实例介绍
2014/06/09 Javascript
jQuery中parents()方法用法实例
2015/01/07 Javascript
javascript性能优化之事件委托实例详解
2015/12/12 Javascript
浅谈javascript控制HTML5的全屏操控,浏览器兼容的问题
2016/10/10 Javascript
Bootstrap基本插件学习笔记之按钮(21)
2016/12/08 Javascript
利用vue.js插入dom节点的方法
2017/03/15 Javascript
jQuery实现字体颜色渐变效果的方法
2017/03/29 jQuery
详解vue组件通信的三种方式
2017/06/30 Javascript
在Vue组件化中利用axios处理ajax请求的使用方法
2017/08/25 Javascript
利用nvm管理多个版本的node.js与npm详解
2017/11/02 Javascript
Bootstrap实现可折叠分组侧边导航菜单
2018/03/07 Javascript
python和C语言混合编程实例
2014/06/04 Python
Python开发的单词频率统计工具wordsworth使用方法
2014/06/25 Python
Python使用内置json模块解析json格式数据的方法
2017/07/20 Python
Python爬取爱奇艺电影信息代码实例
2019/11/26 Python
解决IDEA 的 plugins 搜不到任何的插件问题
2020/05/04 Python
Django前后端分离csrf token获取方式
2020/12/25 Python
挖掘机司机岗位职责
2014/02/12 职场文书
资金主管岗位职责范本
2014/03/04 职场文书
同学聚会主持词
2014/03/18 职场文书
反邪教宣传工作方案
2014/05/07 职场文书
党委书记群众路线对照检查材料思想汇报
2014/10/04 职场文书
2016年元旦致辞
2015/08/01 职场文书
MongoDB连接数据库并创建数据等使用方法
2021/11/27 MongoDB