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

 更新时间:2014年01月26日 10:18:58   作者:  
本篇文章主要介绍了jQuery调用RESTful WCF示例代码(GET方法/POST方法),需要的朋友可以过来参考下,希望对大家有所帮助

不废话了,直奔主题吧

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>

示例代码:点击下载 

相关文章

  • jQuery插件扩展extend的简单实现原理

    jQuery插件扩展extend的简单实现原理

    下面小编就为大家带来一篇jQuery插件扩展extend的简单实现原理。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • jQuery实现鼠标滑过遮罩并高亮显示效果

    jQuery实现鼠标滑过遮罩并高亮显示效果

    本文为大家详细介绍下使用jQuery实现鼠标滑过遮罩高亮显示效果,想必这种效果在网上大家都有见到过,下面是具体的示例,感兴趣的各位可以参考下哈,希望对大家有所帮助
    2013-07-07
  • 40个有创意的jQuery图片和内容滑动及弹出插件收藏集之三

    40个有创意的jQuery图片和内容滑动及弹出插件收藏集之三

    在网页的首页或图片专题页面很多地方都会用到图片滑动插件来循环切换多张图片,并且用户可以点击左右按钮来切换图片。
    2012-01-01
  • 基于jQuery的checkbox全选问题分析

    基于jQuery的checkbox全选问题分析

    这篇文章主要介绍了基于jQuery的checkbox全选问题,结合实例形式分析了jQuery实现全选功能中遇到的问题与相应的解决方法,需要的朋友可以参考下
    2016-11-11
  • 实例详解jQuery的链式编程风格

    实例详解jQuery的链式编程风格

    jQuery中的链式操作,它让代码变得更有层次更简洁,所以这篇文章主要给大家介绍了关于jQuery链式编程风格的相关资料,需要的朋友可以参考下
    2021-06-06
  • JQuery创建DOM节点的方法

    JQuery创建DOM节点的方法

    这篇文章主要介绍了JQuery创建DOM节点的方法,实例分析了jQuery创建元素结点、文本结点、属性结点的相关技巧,需要的朋友可以参考下
    2015-06-06
  • jQuery实现可高亮显示的二级CSS菜单效果

    jQuery实现可高亮显示的二级CSS菜单效果

    这篇文章主要介绍了jQuery实现可高亮显示的二级CSS菜单效果,涉及基本的jquery鼠标事件及页面元素样式动态改变技巧,需要的朋友可以参考下
    2015-09-09
  • 使用jq获取元素值的常见写法总结

    使用jq获取元素值的常见写法总结

    这篇文章给大家总结了使用jq获取元素值的常见写法,文中给大家介绍了详细的代码示例,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2023-12-12
  • Jquery实现带动画效果的经典二级导航菜单

    Jquery实现带动画效果的经典二级导航菜单

    导航菜单在网页中呈现的频率还是比较多的,因为效果相当不错,接下来为大家介绍下使用jquery实现经典二级导航菜单,各位童鞋们快来围观哦
    2013-03-03
  • 使用jQuery处理AJAX请求的基础学习教程

    使用jQuery处理AJAX请求的基础学习教程

    这篇文章主要介绍了使用jQuery处理AJAX请求的基础学习教程,除此之外还引申了链式处理事件回调的写法,由浅入深非常值得借鉴,需要的朋友可以参考下
    2016-05-05

最新评论