您的位置:首页 > 其它

Wcf简单实例1

2016-04-28 13:21 393 查看
一、客户端添加服务引用,并调用

1.使用客户端代理同步调用

static void TestTwo()
{
/*********同步访问********/
Person.PersonServiceClient client = new Person.PersonServiceClient();
string result = client.DoWork(new[] { 1, 3, 5 });
Console.WriteLine(result);

DateTime serverTime = client.GetServerTime();
Console.WriteLine(serverTime);

Dictionary<string, int> dic = client.GetDic();
foreach (var item in dic)
{
Console.WriteLine(item.Key + ":" + item.Value);
}

//服务店List集合,对应客户端数组
string[] strList = client.GetListStr();
Console.WriteLine(string.Join(",", strList));

Person.Person[] list = client.GetList();
foreach (var item in list)
{
Console.WriteLine(item.ID + "-" + item.Name + "-" + item.Birthday);
}
//关闭连接
client.Close();
}


2.使用客户端代理异步调用

static void TestThree()
{
/******异步访问******/
Person.PersonServiceClient client = new Person.PersonServiceClient();
Task<string> result = client.DoWorkAsync(new[] { 1, 3, 5 });
Task<DateTime> serverTime = client.GetServerTimeAsync();
Console.WriteLine(result.Result);
Console.WriteLine(serverTime.Result);

//关闭连接
client.Close();
Console.WriteLine("end");
}


客户端配置:

public class PersonService : IPersonService
{
public string DoWork(int[] numbers)
{
return string.Join("|", numbers);
}
public Dictionary<string, int> GetDic()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("one", 1);
dic.Add("two", 2);

return dic;
}
public List<Person> GetList()
{
List<Person> list = new List<Person>();

list.Add(new Person()
{
ID = 1,
Name = "张三",
Birthday = new DateTime(1990, 1, 1)
});

list.Add(new Person()
{
ID = 2,
Name = "李四",
Birthday = new DateTime(1991, 1, 1)
});
return list;
}
public DateTime GetServerTime()
{
return DateTime.Now;
}
public List<string> GetListStr()
{
List<string> list = new List<string>();
list.Add("张三");
list.Add("王芳");
return list;
}
}


View Code
服务端使用默认配置

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: