我的第一个WCF

第一步:先定义服务契约

 [ServiceContract]
    public  interface  IService
    {
        [OperationContract]
        string Show();
        
    }

第二步:定义服务类

 public class Services : IService
    {
        public string Show()
        {
            return "Hello world";
        }
    }

第三步:在控制台定义托管服务,这些配置可以用app.config配置,也可以手写代码,这里只放出手写代码的方式

 static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(Services));

            //添加端点 ABC
            Uri address = new Uri("http://localhost:1111/Msg");  //地址
            Binding binding = new  NetHttpBinding();  //绑定
            host.AddServiceEndpoint(typeof(IService), binding, address);  //添加端点信息

            //发布元数据,WSDL
            ServiceMetadataBehavior meta = new ServiceMetadataBehavior();
            meta.HttpGetUrl = new Uri("http://localhost:2222/Msg");  //指定地址
            meta.HttpGetEnabled = true;  //是否允许Get请求
            host.Description.Behaviors.Add(meta);   //将元数据对象添加到服务行为中

            host.Open();
            Console.WriteLine("服务开启成功");
            Console.ReadLine();
            host.Close();
            Console.WriteLine("服务关闭成功");
        }

第四步,定义客户端测试,客户端可以是任何一种程序,这里我就用控制台来测,方便点,首先新建控制台应用程序,然后开启我们刚才创建的托管服务,之后添加服务应用,输入我们定义的元数据地址,然后写上代码测试就ok了。

1,开启托管服务

2、添加服务引用

3、填入元数据的服务地址

4、点击转到,选择服务,最后确定

6、代码测试

static void Main(string[] args)
        {
            using (ServiceReference2.ServiceClient client = new ServiceReference2.ServiceClient())
            {
                Console.WriteLine(client.Show());
            }
        }

最后测试结果

posted @ 2016-05-04 10:00  IsCarrie  阅读(186)  评论(0编辑  收藏  举报