1.定义WCF服务协定
[ServiceContract]
public interface IUser
{
[OperationContract]
string ShowName(string name); }
2.实现WCF服务协定
public class User : IUser
{
public string ShowName(string name) { string wcfName = string.Format("Show name:{0}", name); return wcfName; } }
3.承载并运行WCF服务
3.1 创建URL基地址
Uri baseAddress = new Uri("http://localhost:8080/User");
3.2 创建ServiceHost示例来承载Service
ServiceHost serviceHost = new ServiceHost(typeof(User),baseAddresses);
3.3 创建ServiceEndpoint示例
host.AddServiceEndpoint(typeof(IUser), new WSHttpBinding(), "User");
3.4 开启元数据交换
//将HttpGetEnabled属性设置为true
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true; //将行为添加到Behaviors中 host.Description.Behaviors.Add(smb);
3.5 开启ServierHost以监听消息
//打开宿主
host.Open();
(也可以在server的app.config中配置)
ServiceHost host = new ServiceHost(typeof(User));
host.Open();
<?xml version="1.0" encoding="utf-8" ?>
<configuration> <system.serviceModel> <services> <service name="WcfServiceLibrary.User"> <host> <baseAddresses> <add baseAddress="http://localhost:8080/User"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="WcfServiceLibrary.IUser"></endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
4.创建WCF客户端
4.1添加Service Reference,address为server中的baseaddress
4.2调用服务协定(Service contract)
5.Config WCF client
在client中的app.config配置
<system.serviceModel>
<bindings> <wsHttpBinding> <binding name="WSHttpBinding_IUser" /> </wsHttpBinding> </bindings> <client> <endpoint address="http://localhost:8080/User" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IUser" contract="ServiceReference.IUser" name="WSHttpBinding_IUser"> <identity> <userPrincipalName value="xxxx" /> </identity> </endpoint> </client> </system.serviceModel>