WCF学习记录(一)

     在这里先简单记录下WCF配置的过程,关于WCF详解,下次再做具体描述。

    1. Contract及其实现

       a.

 [ServiceContract(Namespace = "http://www.******.com")]
    public interface IHello
    {
        [OperationContract]
        void Hello();
    }

       b. 如果方法参数是复杂对象,需要加DataMember标签,如:

[ServiceContract(Namespace = "http://www.。。。。。.com")]
    public interface IComplexHello
    {
        [OperationContract]
        string Hello(Person personInfo);
    }

    [DataContract(Namespace = "http://www.。。。。t.com")]
    public class Person
    {
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Title { get; set; }
    }

          

 public class HelloService : IHello
    {
        public void Hello()
        {
            Console.WriteLine("hello");
        }
    }

        c. 服务实现 CallbackContract

[ServiceContract(Namespace = "http://www.abc.com")]
public interface IHelloCallbackContract
{
    [OperationContract(IsOneWay = true)]
    void Reply(string responseToGreeting);
}

[ServiceContract(Namespace = "http://www.abc.com", CallbackContract = typeof(IHelloCallbackContract))]
public interface IDuplexHello
{
    [OperationContract(IsOneWay = true)]
    void Hello(string greeting);
}

    2. Host  配置

           配置文件可以用VS自带的tool创建,Tools->WCF Service Configuration Editor.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <netTcpBinding>
                <binding name="NewBinding0" />
            </netTcpBinding>
        </bindings>
        <services>
            <service name="Service.HelloService">
                <endpoint address="net.tcp://localhost:5431/HelloService" binding="netTcpBinding"
                    bindingConfiguration="" contract="Contract.IHello" />
            </service>
        </services>
    </system.serviceModel>
</configuration>
using (var server = new ServiceHost(typeof(HelloService)))
            {
                server.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.ReadLine();
            }

3. 客户端代理创建

                var tcpBinding = new NetTcpBinding();
                var endpointAddress = new EndpointAddress("net.tcp://localhost:5431/HelloService");
                var channel = new ChannelFactory<IHello>(tcpBinding, endpointAddress);
                var proxy = channel.CreateChannel();
                proxy.Hello();
                Console.WriteLine("Press <ENTER> to exit.");
                Console.ReadKey();

      如果是实现了CallbackContract,则需要

var context = new InstanceContext(new HelloCallbackService());
var duplexChannel = new DuplexChannelFactory<IDuplexHello>(context, myBinding,endpointAddress);

);

原文地址:https://www.cnblogs.com/aeolia/p/3611235.html