WCF 配置终结点并调用服务

wcf通过xml文件配置终结点什么的感觉有点小麻烦,个人还是觉得用代码形式配置比较好,当然在发布的时候可能会比较麻烦,需要重新编译。。。

下面将wcf service寄宿在控制台应用程序中并配置终结点并通过HTTP-GET发布元数据

using (var host = new ServiceHost(typeof (Service1),
                                              new Uri("http://localhost:8888/Service1")))
            {
                host.AddServiceEndpoint(typeof (IService1), new BasicHttpBinding(), string.Empty);
                    //address为string.Empty直接使用基地址
                var metadataBehavior =
                    host.Description.Behaviors.Find<ServiceMetadataBehavior>(); //指定元数据行为以便发布元数据
                if (metadataBehavior == null) //必须要判断是为空
                {
                    metadataBehavior = new ServiceMetadataBehavior
                        {
                            HttpGetEnabled = true //将HttpGetEnabled设为true
                        };
                    host.Description.Behaviors.Add(metadataBehavior);
                }
                host.Opened += delegate
                    {
                        Console.WriteLine("服务已经启动");
                    };
                host.Open();
                Console.Read();
            }

  

客服端代理服务:

 using (var factory =
                new ChannelFactory<IService1>(new BasicHttpBinding(),
                                              new EndpointAddress("http://localhost:8888/Service1")))
            {
                IService1 channelproxy = factory.CreateChannel();
                using (channelproxy as IDisposable)
                {
                    Console.WriteLine(channelproxy.GetData(55555));
                }
                Console.Read();
            }

注意宿主配置的终结点必须和客服端配置的终结点地址要保持一致,否则无法找到终结点而报异常。

原文地址:https://www.cnblogs.com/objectboy/p/3767312.html