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

    欢迎大家扫描下面二维码成为我的客户,为你服务和上云

  • 相关阅读:
    编译安装LEMP
    eAccelerator配置和使用指南
    /dev/null的用途
    分库分表
    JVM
    SOFA 数据透析
    HTTPS
    SOFA 通信
    分布式锁
    mysql 锁
  • 原文地址:https://www.cnblogs.com/shanyou/p/1348831.html
Copyright © 2020-2023  润新知