none
WCF Rest谁比较熟悉?有编程经验的介绍一下~ RRS feed

  • 问题

  •     WCF Rest谁比较熟悉?有编程经验的介绍一下~ 我对这个陌生,很想请教一下,最好能给个可以运行的示例代码
    Frank.Xu Lei--谦卑若愚,好学若饥
    专注于.NET平台下分布式应用系统开发和企业应用系统集成
    Focus on Distributed Applications Development and EAI based on .NET
    老徐的博客:http://www.cnblogs.com/frank_xl
    2009年6月9日 12:38
    版主

答案

  • 你好,

    我写了个sample:

    web.config
     <system.serviceModel>
      <bindings>
       <webHttpBinding>
        <binding name="mywebHttpBinding"></binding>
       </webHttpBinding>
      </bindings>
      <behaviors>
          <endpointBehaviors>
            <behavior name="HttpEnableBehavior">
              <webHttp/>
            </behavior>
          </endpointBehaviors>
       <serviceBehaviors>
        <behavior name="WCF_REST.Service1Behavior">
         <serviceMetadata httpGetEnabled="true"/>
        </behavior>
       </serviceBehaviors>
      </behaviors>
      <services>
       <service behaviorConfiguration="WCF_REST.Service1Behavior" name="WCF_REST.Service1">
        <endpoint behaviorConfiguration="HttpEnableBehavior"   bindingConfiguration="mywebHttpBinding" address="" binding="webHttpBinding" contract="WCF_REST.IService1">
         <identity>
          <dns value="localhost"/>
         </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       </service>
      </services>
     </system.serviceModel>

    IService1.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Web;

    namespace WCF_REST
    {
        // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.

        [ServiceContract]
        public interface IService1
        {   //test http://.../Service1.svc/GetData?q=aaa
            [WebGet(UriTemplate="*")]
            [OperationContract]
            Message GetData();
            //test http://.../Service1.svc/Get/myparameter
            [WebGet(UriTemplate="Get/{param}")]
            [OperationContract]
            string GetData2(string param);

            [WebInvoke(Method="POST",UriTemplate="Post")]
            [OperationContract]
            string PostData();
        }
    }

    Service1.svc.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Web;

    namespace WCF_REST
    {
        // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config.

        public class Service1 : IService1
        {
            public Message GetData()
            {
                WebOperationContext woc = WebOperationContext.Current;
                woc.OutgoingResponse.Headers["Content-Type"] = "text/xml";
               string querystring="";
               if (woc.IncomingRequest.UriTemplateMatch.QueryParameters.Count > 0)
               {
                   querystring = woc.IncomingRequest.UriTemplateMatch.QueryParameters[0];
               }
              
                Message response = Message.CreateMessage(MessageVersion.None, "*", "Simple response. Query String: " + querystring);
                return response;
            }

            public string GetData2(string param)
            {
              
                string response = "Simple response. Param: " + param;
                return response;
            }

            public string PostData()
            {
             string posteddata=   OperationContext.Current.RequestContext.RequestMessage.ToString();
             return "Posted at: " + DateTime.Now.ToString() + " Posted data: " + posteddata;
            }
        }
    }

     

    Test code.
    aspx.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Net;
    using System.IO;
    using System.Threading;

    namespace WCF_REST
    {
        public partial class _Default : System.Web.UI.Page
        {
            byte[] buffer;
            protected void Page_Load(object sender, EventArgs e)
            {//init buffer
             //buffer contains the data send to REST service
                string s = "<test>Hello World!</test>";
                buffer= System.Text.Encoding.Default.GetBytes(s);

                //note to change the url below to test
                HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create("http://localhost:1329/Service1.svc/Post");
                hwr.Method = "POST";

                //Important thing here. If it's not added we'll get 415
                //The Content-Type header is essential when using RESTful
                //services in general, but is especially important when
                //making requests to RESTful services.
                //If you don't have a Content-Type header in your HTTP
                //request to a WCF service, you'll always get a
                //"415 Missing Content Type" status code.
                //You don't need the Content-Type header when making
                //a GET request, since there isn't any entity body when
                //making a GET request.

                hwr.ContentType=@"text/xml";

                //sync
                using (Stream postStream = hwr.GetRequestStream())
                {
                    postStream.Write(buffer, 0, buffer.Length);
                    postStream.Close();
                    HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
                    using (Stream respStream = response.GetResponseStream())
                    {
                        using (StreamReader streamRead = new StreamReader(respStream))
                        {
                            //render the result retrieved from REST service
                            Response.Write(streamRead.ReadToEnd());
                        }
                    }
                }

                ////async
                //bool flag=true;
                //hwr.BeginGetRequestStream((a) =>
                //{
                //    HttpWebRequest request = (HttpWebRequest)a.AsyncState;
                //    Stream postStream = request.EndGetRequestStream(a);
                //    postStream.Write(buffer, 0, buffer.Length);
                //    postStream.Close();
                //    request.BeginGetResponse((a1) =>
                //    {
                //        HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(a1);
                //        Stream streamResponse = resp.GetResponseStream();
                //        StreamReader streamRead = new StreamReader(streamResponse);
                //        string responseString = streamRead.ReadToEnd();
                //        //render the result retrieved from REST service
                //        Response.Write(responseString);
                //        // Close the stream object.
                //        streamResponse.Close();
                //        streamRead.Close();
                //        // Release the HttpWebResponse.
                //        resp.Close();
                //        flag=false;
                //    }, request);
                //}, hwr);

                ////
                //while(flag){Thread.Sleep(1000);}
            }
        }
    }

    涵盖了基本REST的使用。


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    2009年6月11日 6:05
    版主

全部回复

  • 你好,

    我写了个sample:

    web.config
     <system.serviceModel>
      <bindings>
       <webHttpBinding>
        <binding name="mywebHttpBinding"></binding>
       </webHttpBinding>
      </bindings>
      <behaviors>
          <endpointBehaviors>
            <behavior name="HttpEnableBehavior">
              <webHttp/>
            </behavior>
          </endpointBehaviors>
       <serviceBehaviors>
        <behavior name="WCF_REST.Service1Behavior">
         <serviceMetadata httpGetEnabled="true"/>
        </behavior>
       </serviceBehaviors>
      </behaviors>
      <services>
       <service behaviorConfiguration="WCF_REST.Service1Behavior" name="WCF_REST.Service1">
        <endpoint behaviorConfiguration="HttpEnableBehavior"   bindingConfiguration="mywebHttpBinding" address="" binding="webHttpBinding" contract="WCF_REST.IService1">
         <identity>
          <dns value="localhost"/>
         </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       </service>
      </services>
     </system.serviceModel>

    IService1.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Web;

    namespace WCF_REST
    {
        // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.

        [ServiceContract]
        public interface IService1
        {   //test http://.../Service1.svc/GetData?q=aaa
            [WebGet(UriTemplate="*")]
            [OperationContract]
            Message GetData();
            //test http://.../Service1.svc/Get/myparameter
            [WebGet(UriTemplate="Get/{param}")]
            [OperationContract]
            string GetData2(string param);

            [WebInvoke(Method="POST",UriTemplate="Post")]
            [OperationContract]
            string PostData();
        }
    }

    Service1.svc.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Web;

    namespace WCF_REST
    {
        // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config.

        public class Service1 : IService1
        {
            public Message GetData()
            {
                WebOperationContext woc = WebOperationContext.Current;
                woc.OutgoingResponse.Headers["Content-Type"] = "text/xml";
               string querystring="";
               if (woc.IncomingRequest.UriTemplateMatch.QueryParameters.Count > 0)
               {
                   querystring = woc.IncomingRequest.UriTemplateMatch.QueryParameters[0];
               }
              
                Message response = Message.CreateMessage(MessageVersion.None, "*", "Simple response. Query String: " + querystring);
                return response;
            }

            public string GetData2(string param)
            {
              
                string response = "Simple response. Param: " + param;
                return response;
            }

            public string PostData()
            {
             string posteddata=   OperationContext.Current.RequestContext.RequestMessage.ToString();
             return "Posted at: " + DateTime.Now.ToString() + " Posted data: " + posteddata;
            }
        }
    }

     

    Test code.
    aspx.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Net;
    using System.IO;
    using System.Threading;

    namespace WCF_REST
    {
        public partial class _Default : System.Web.UI.Page
        {
            byte[] buffer;
            protected void Page_Load(object sender, EventArgs e)
            {//init buffer
             //buffer contains the data send to REST service
                string s = "<test>Hello World!</test>";
                buffer= System.Text.Encoding.Default.GetBytes(s);

                //note to change the url below to test
                HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create("http://localhost:1329/Service1.svc/Post");
                hwr.Method = "POST";

                //Important thing here. If it's not added we'll get 415
                //The Content-Type header is essential when using RESTful
                //services in general, but is especially important when
                //making requests to RESTful services.
                //If you don't have a Content-Type header in your HTTP
                //request to a WCF service, you'll always get a
                //"415 Missing Content Type" status code.
                //You don't need the Content-Type header when making
                //a GET request, since there isn't any entity body when
                //making a GET request.

                hwr.ContentType=@"text/xml";

                //sync
                using (Stream postStream = hwr.GetRequestStream())
                {
                    postStream.Write(buffer, 0, buffer.Length);
                    postStream.Close();
                    HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
                    using (Stream respStream = response.GetResponseStream())
                    {
                        using (StreamReader streamRead = new StreamReader(respStream))
                        {
                            //render the result retrieved from REST service
                            Response.Write(streamRead.ReadToEnd());
                        }
                    }
                }

                ////async
                //bool flag=true;
                //hwr.BeginGetRequestStream((a) =>
                //{
                //    HttpWebRequest request = (HttpWebRequest)a.AsyncState;
                //    Stream postStream = request.EndGetRequestStream(a);
                //    postStream.Write(buffer, 0, buffer.Length);
                //    postStream.Close();
                //    request.BeginGetResponse((a1) =>
                //    {
                //        HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(a1);
                //        Stream streamResponse = resp.GetResponseStream();
                //        StreamReader streamRead = new StreamReader(streamResponse);
                //        string responseString = streamRead.ReadToEnd();
                //        //render the result retrieved from REST service
                //        Response.Write(responseString);
                //        // Close the stream object.
                //        streamResponse.Close();
                //        streamRead.Close();
                //        // Release the HttpWebResponse.
                //        resp.Close();
                //        flag=false;
                //    }, request);
                //}, hwr);

                ////
                //while(flag){Thread.Sleep(1000);}
            }
        }
    }

    涵盖了基本REST的使用。


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    2009年6月11日 6:05
    版主
  • 谢谢,我补充一下,大家对WCF Rest也好有个了解:
    WCF中国研发团队博客: WCF中的REST架构三 (支持AJAX的WCF Service – 使用服务) WCF中的REST架构二 (支持AJAX的WCF服务 - 创建服务) WCF中的REST架构一(REST 概述)
    WCF中的 REST架构一(REST 概述) 不同的人似乎对REST有不同的定义,有些定义是非常严格的,而有些则是比较自由的。我倾向于认为REST架构存在于一个连续的范围里, 如图所示: 我们可以认为REST背后隐含的基本理念如下:       越简单越好         Web一直是非常成功的。         Web是很简单的         Web设计要遵循一些指导性原则,而这些原则在过去很长一段时间内都是可靠的。         Web 服务的设计要以 Web的方式。

    尽管不同的人对 REST有不同的定义,但可以肯定的是存在一些特征来影响一个服务是否是RESTful的,或者它能不能被认为是RESTful, 或者它能否落在上面这个连续范围内的某个位置。这里列出一些(并不是全部)特征:

    ·         对HTTP 方法(GET,PUT,POST,DELETE是主要的HTTP方法)的合理使用——HI-REST端倾向于对具体方法用于具体的情景进行严格的规定。例如一个HI-REST的实现中使用GET方法获取,DELETE方法用来删除,PUT方法用来插入或者更新,而POST方法则用来附加。而LO-REST的解决方案则可能使用POST方法做插入,更新,删除和附加操作。

    ·         对数据表现形式的选择——HI-REST解决方案倾向于选择标准的数据表现形式,而一些LO-REST解决方案则认为POX也是一个不错的选择。

    ·         对良好构造的URI的使用——HI-REST解决方案倾向于使用描述性的URI而一般情况下不使用查询字符串,而我们在一些LO-REST解决方案中可以看到对查询字符串的使用。

    ·         其他:有效负荷中包含指向相关信息的链接,使用合适的HTTP 响应代码。

    我没有在什么是REST的基础上给出一个严格的定义,原因并不是我觉得这不重要。原因是,从WCF的角度,一个专门的定义无关紧要。WCF支持范围两端的REST架构(HI-REST和LO-REST)。事实上,在下一篇文章中,我将建立一个LO-REST的实现,同时在之后的文章中,我将演示HI-REST端的实现。

    如果上面这些对你来说都没有什么意义,也没有关系,下面的文章将提供具体的实例。

     

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/WCFToolsBloggers/archive/2008/09/02/2865038.aspx


    Frank.Xu Lei--谦卑若愚,好学若饥
    专注于.NET平台下分布式应用系统开发和企业应用系统集成
    Focus on Distributed Applications Development and EAI based on .NET
    老徐的博客:http://www.cnblogs.com/frank_xl
    2009年6月11日 12:53
    版主
  • 谢谢,现在看你的回复~ 也很有帮助~
    Frank Xu Lei--谦卑若愚,好学若饥
    专注于.NET平台下分布式应用系统开发和企业应用系统集成
    Focus on Distributed Applications Development and EAI based on .NET
     

    老徐的网站】:http://www.frankxulei.com/

    老徐的博客】:http://www.cnblogs.com/frank_xl/

    【中文论坛】:微软WCF中文技术论坛
    【英文论坛】:微软WCF英文技术论坛

    2010年5月24日 6:22
    版主