创建WCF服务

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>

 

转载于:https://www.cnblogs.com/xanadu123/p/4607260.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值