我们在键盘上跳舞,演绎最美的人生

WCF REST<2>: 消费WCF REST 服务

在上一篇《WCF Rest<1> 搭建简单的WCF REST 服务》,中,我们已经搭建了一个WCF REST 服务,在本篇中,主要介绍,如何在WinForm程序和ASP.NET程序里消费此服务

一、在ASP.NET中通过JQuery消费REST服务

1、为了简化测试,不考虑跨域调用的问题,我们在原来的服务中添加一个ASPX文件,并在此文件中编写如下测试代码: 

<body>
    <form id="form1" runat="server">
    <div>
        <input id="txtHelloWorld" type="text" /><br />
    <input type ="button" value ="helloworld" id="btn1"/>
        <input type="button" value="customers" id="btn2" />
    </div>
    </form>
    <script src="jquery-1.7.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btn1").click(function() {
                var url = "http://localhost:5460/Customer/XMLService/HelloWorld";
              
                var value = $("#txtHelloWorld").val();
                
                var data = { "world": value };
                var postData = JSON.stringify(data);
              
                $.ajax({
                    type: 'POST',
                    url: url,
                    data:postData,
                    dataType: "json",
                    contentType: "application/json",
                    success: function(result) {
                        alert(result);
                    },
                    error: function(error) {
                        alert(error);
                    }
                  
                });
            }
            );
            $("#btn2").click(function () {
                var value = $("#txtHelloWorld").val();
                var url = "http://localhost:5460/Customer/XMLService/Customers/" + value;
                 
                $.ajax({
                    type: 'GET',
                    url: url,
           
                    success: function (result) {
                        var t = JSON.stringify(result);
                        alert(t);
                    },
                    error: function (error) {
                        alert(error);
                    },
                    dataType: "json",
                    contentType: "application/json"
                });
            }
          );
        });

      
    </script>
</body>

  代码中可以看到,这里有两个按钮,一个用来测试GET的REST服务,一个用来测试POST的REST服务,这里注意的是,不够使GET还是POST,我们都设置了dataType为Json,contentType为application/json,而且在POST测试时,POST到服务器的data对象时json对象的字符串格式,而非原始JSON对象

     一切准备就绪,F5进入调试状态,出现如图界面:

在文本框中输入任意字符,进行然后点击helloworld按钮进行POST测试:

调用成功。 再次在文本框中输入任意字符,然后按customers按钮进行GET测试:

 

GET方式调用也成功了。

到这里,看似一切顺利,但为何上面有段文字我用红色标注了呢?多说无益,让我们来看看改成红色标注的那样,直接传送JSON格式的data对象会发生什么吧!

看到没,出现了400 Bad Request错误,为何会出现这样的问题,为何会这样,不太懂,还希望有人可以指出。

 

二、在WinForm中消费WCF REST 服务

 新增一个WinFrom项目,添加两个button,并对相应的click中编写GET和POST请求:

 #region Rest

        /// <summary>
        /// POST
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string serviceUrl = "http://localhost:5460/Customer/XMLService/HelloWorld";
            string temp = textBox1.Text.Trim();
            var httpClient = new HttpClient();
            var postData = "{\"world\":\"" + temp + "\"}";
            var webclient = new WebClient();
            webclient.Encoding = System.Text.Encoding.UTF8;
            webclient.Headers.Add("Content-Type", "application/json");
            string isSuccess = webclient.UploadString(serviceUrl, "POST", postData);
            MessageBox.Show(isSuccess);
        }

        /// <summary>
        /// GET
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            string serviceUrl = "http://localhost:5460/Customer/XMLService/Customers/aaaa";
            var webclient = new WebClient();
            Uri uri = new Uri(serviceUrl, UriKind.Absolute);
            if (!webclient.IsBusy)
            {
                webclient.Encoding = System.Text.Encoding.UTF8;
                string json = webclient.DownloadString(uri);
                MessageBox.Show(json);
            }
        }

        #endregion

  按F5进入调试,弹出如下的界面:

 

 

在这里,我们点击REST方式下面的POST按钮来测试POST操作:

调用成功,我们再来点击REST方式下的GET按钮来进行GET操作测试:

 

在这里发现,GET操作也顺利完成。

*细心的人也会发现,在这个测试窗口中,有REST方式测试和SOAP方式测试,主要是因为这个REST服务并非只是REST服务,它还同时暴露了一个basicHttpBinding的Soap服务,SOAP测试就是通过添加服务引用的方式进行调用,跟传统意义的WCF服务没有区别,故这里就不再啰嗦了。收工。

 

posted @ 2013-03-30 18:10  嘉应子  阅读(564)  评论(0编辑  收藏  举报