JQuery calls the RESTful WCF sample code of GET method and POST method


Cut the crap and get to the point

WCF client:

< % @ ServiceHost Language = “c #” Debug = “true” Service = “ajaxSample. The HelloWorld CodeBehind” = “HelloWorld. SVC. Cs Factory” = “System. The ServiceModel. Activation. WebServiceHostFactory” % >

Note: if you don’t add the Factory, the WCF, http://localhost/helloWorld.svc/Hello/person/name will not be able to use similar to directly access restful way.

Also remove < from web.config; EnableWebScript / > Is similar to:

< System. ServiceModel>       < Behaviors>           < EndpointBehaviors>               < Behaviors name = “ajaxSample. HelloWorldAspNetAjaxBehavior >”                   < ! - < EnableWebScript / > - >               < / behavior>           < / endpointBehaviors>       < / behaviors>       < ServiceHostingEnvironment aspNetCompatibilityEnabled = “true”           MultipleSiteBindingsEnabled = “true” / >       < Services>           < The service name = “ajaxSample. The HelloWorld” >               < The endpoint address = "" behaviorConfiguration =” ajaxSample. HelloWorldAspNetAjaxBehavior”                   The binding = “webHttpBinding” contract = “ajaxSample. The HelloWorld / >”           < / service>       < / services>   < / system. ServiceModel>

Okay, let’s start writing code. Since there are two ways to GET/POST in WCF calls, let’s write a sample method for several common cases:

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 only Restful methods
        /// </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>
        /// can only Get Restful methods
        /// </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>
        /// can Get and Post Restful methods
        /// </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>
        /// general method of Post only (note: Post mode, BodyStyle must be set to WrappedRequest or 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>
        /// only regular methods of 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 calling code:

<script type="text/javascript">
    $().ready(function () {

 
        $.post("HelloWorld.svc/PostRestfulTest/111/222", function (data) {
            alert("PostRestfulTest Successful call, the return value is: " + data);
        })

        $.get("HelloWorld.svc/GETRestfulTest/333/444", function (data) {
            alert("GETRestfulTest Successful call, the return value is: " + data);
        })

        $.get("HelloWorld.svc/RestfulTest/555/666", function (data) {
            alert("RestfulTest GET Method is successfully invoked, and the return value is: " + data);
        })

 
        $.post("HelloWorld.svc/RestfulTest/777/888", function (data) {
            alert("RestfulTest POST Method is successfully invoked, and the return value is: " + data);
        })

 
        $.get("HelloWorld.svc/GETTest", { person: "aaa", welcome: "bbb" }, function (data) {
            alert("GETTest  Successful call, the return value is: " + data);
        });

 
        $.ajax({
            url: "HelloWorld.svc/PostTest",
            type: "POST",
            contentType: "application/json",
            data: '{"person":"ccc","welcome":"ddd"}',
            dataType: "html",
            success: function (data) { alert("PostTest Successful call, the return value is: " + data); }
        });
    })
</script>

Sometimes, the method exposed by WCF may need some sensitive information as parameters (such as user name/user ID, etc.), then if directly using js to call WCF, this part of information may be leaked to the client side, in this scenario, we often use a server side ashx to do the transfer

TestService. SVC

using System.ServiceModel;

namespace ashx_jQuery
{
     [ServiceContract]
    public class TestService 
    {
         /// <summary>
         //Gets the current user's salary for the specified month
         /// </summary>
         /// <param name="userId"></param>
         /// <param name="month"></param>
         /// <returns></returns>
         [OperationContract]
        public double GetSalary(int userId,int month)
        {
            if (month == 1)//It's just a demonstration
            {
                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>
        /// gets the current user ID
        /// </summary>
        /// <returns></returns>
        private int GetUserId() 
        {
            return 1;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

JQuery calls:

<%@ 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>

Sample code: (link: http://xiazai.jb51.net/201401/jquery\_ajax\_wcf\_rest (jb51.net). Rar)