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();       }

相关文章

1.使用ajax调用varxhr;functioninvoke(){if(window.ActiveXO...
               好不容易把WebService服务器...
1新建一个工程项目用来做服务端增加一个MyService1类文件pac...
packagecom.transsion.util;importjava.io.BufferedReader;i...
再生产wsdl文件时重写描述文件1usingSystem;2usingSystem.Co...
一般情况下,使用eclipse自带的jax-ws生成webservice会自动生...