微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

RESTful WCF

相较 WCF、WebService 使用 SOAP、WSDL、WS-* 而言,几乎所有的语言和网络平台都支持 HTTP 请求。我们无需去实现复杂的客户端代理,无需使用复杂的数据通讯方式既可以将我们的服务暴露给任何需要的人,无论他使用 VB、Ruby、JavaScript,甚至是 HTML FORM,或者直接在浏览器地址栏输入。

WCF 3.5 引入了 WebGetAttribute、WebInvokeAttribute、UriTemplate 来增加对 REST 的支持,这使得我们用很简单的方式就可以实现 RESTful WCF Service。

可参考以下几篇文章:

《深入浅出REST》 : 作者 Stefan Tilkov译者 苑永凯

《Web 编程模型》 : MSDN文档
《使用 WCF 和 .NET Framework 3.5 进行 HTTP 编程》 : Justin Smith

Twitter WCF Client

下面我们来看一个简单的例子:

[ServiceContract]
public interface IService
{
     [OperationContract]
     [WebGet]
     string EchoWithGet(string s);

     [OperationContract]
     [WebInvoke]
     string EchoWithPost(string s);
}

 

public class Service : IService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }

 

static void Main(string[] args)
       {
           AppDomain.CreateDomain("Server").DoCallBack(delegate
           {
               ServiceHost host = new ServiceHost(typeof(Service),new Uri("http://localhost:8020"));
               host.AddServiceEndpoint(typeof(IService),new BasicHttpBinding(),"Soap");
               ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService),new WebHttpBinding(),"Web");
               endpoint.Behaviors.Add(new WebHttpBehavior());

               host.open();
           });
           using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8020/Web")))
           {
               IService channel = wcf.CreateChannel();

               string s;

               Console.WriteLine("Calling EchoWithGet by HTTP GET: ");
               s = channel.EchoWithGet("Hello,world");
               Console.WriteLine("   Output: {0}",s);

               Console.WriteLine("");
               Console.WriteLine("This can also be accomplished by navigating to");
               Console.WriteLine("http://localhost:8020/EchoWithGet?s=Hello,world!");
               Console.WriteLine("in a web browser while this sample is running.");

               Console.WriteLine("");

               Console.WriteLine("Calling EchoWithPost by HTTP POST: ");               s = channel.EchoWithPost("Hello,world");               Console.WriteLine("   Output: {0}",s);           }           Console.ReadLine();       }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐