数据契约
wcf中的数据传递到客户端必须是可序列化的,这点和.net remoting ,web service是相同的,所有当我们把复杂的数据传递到客户端时,
必须使用到数据契约,时数据能正常传递到客户端.
数据契约在wcf只是一个特性,或者说是声明型语句,[DataContract] and [DataMember] 它们都在System.Runtime.Serialization中定义.
首先 还是先把解决方案的截图俯上 一个客户端,一个契约类库,一个Wcf服务端
好了 分别把各个部分的实现代码贴上:
MyLibrary:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
namespace MyLibrary
{
[DataContract]
public class User
{
private string _name;
private int _age;
[DataMember]
public string Name
{
get{return _name;}
set{_name=value;}
}
[DataMember]
public int Age
{
get{return _age;}
set{_age=value;}
}
public User(string name,int age)
{
_name=name;
_age=age;
}
}
[ServiceContract]
public interface IContact
{
[OperationContract]
User GetUserInfo(string name);
}
}
MyWcf:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using MyLibrary;
namespace MyWcf
{
public class Contact : IContact
{
List<User> users = new List<User>();
public Contact()
{
users.Add(new User("trampt", 23));
users.Add(new User("stray", 25));
users.Add(new User("cnblogs", 25));
}
public User GetUserInfo(string name)
{
return users.Find(u => u.Name == name);
}
}
class Program
{
static void Main(string[] args)
{
using(ServiceHost host=new ServiceHost(typeof(Contact)))
{
host.AddServiceEndpoint(typeof(MyLibrary.IContact), new NetTcpBinding(), "net.tcp://localhost:8091/Contact");
host.Open();
Console.WriteLine("wait for client request");
Console.ReadLine();
}
}
}
}
Client:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using MyLibrary;
using System.ServiceModel.Channels;
namespace Client
{
class Program
{
static void Main(string[] args)
{
MyLibrary.IContact contact = ChannelFactory<IContact>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8091/Contact"));
User user = contact.GetUserInfo("trampt");
Console.WriteLine(user.Name+" is "+user.Age+" old!");
Console.ReadLine();
}
}
}
好了 首先运行服务器端的WCF服务 其次运行客户端服务 我们可以看到一下效果:
运行成功..
当我们把User类的[DataContract]或者[DataMember]去掉,看我们的程序还能成功运行吗,自己上机体验下,便见分晓.