麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > JavaScript > 正文

jQuery調用RESTful WCF示例代碼(GET方法/POST方法)

2019-11-20 21:12:06
字體:
來源:轉載
供稿:網友

不廢話了,直奔主題吧

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>

示例代碼:點擊下載 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 久久精品一区视频 | 在线播放亚洲精品 | 成人黄色短视频在线观看 | 真人一级毛片免费 | 一区二区久久久久草草 | 看国产毛片 | 91 视频网站 | 特级毛片全部免费播放器 | 国产色视频免费 | 午夜激情视频网站 | 午夜国内精品a一区二区桃色 | av免播放 | 久久久久se| 国产69久久精品成人看 | 中国老女人一级毛片视频 | 看91视频 | 久久精品国产精品亚洲 | 中文字幕欧美亚洲 | 国产一区二精品区在线 | 午夜精品久久久久久久96蜜桃 | www.狠狠操.com | 欧美一级爱操视频 | 日本高清黄色片 | 青草久久久久 | 黄色毛片视频在线观看 | 日本精品视频一区二区三区四区 | 国产999精品久久久久 | 最新久久免费视频 | 亚洲欧美日韩一区二区三区在线观看 | 黄视频在线网站 | 深夜毛片免费看 | 国产18视频 | 欧美一级高潮 | 精品中文视频 | 精品二区在线观看 | 黄色免费影片 | 精品一区二区在线观看视频 | 亚洲国产在 | hdhdhdhd19日本人 | 精品国产一区二区三区成人影院 | 亚洲一区久久 |