[WCF 学习笔记] 10. 行为控制

在完成服务契约设计和服务实现后,我们可以设置该服务的运行期行为(Behavior)。这些行为包括 Service Behaviors、Endpoint Behaviors、Contract Behaviors、Operation Behaviors。

有关所有行为的说明,可以查看 ms-help://MS.MSSDK.1033/MS.NETFX30SDK.1033/WCF_con/html/5c5450ea-6af1-4b75-a267-613d0ac54707.htm。

以下就常用的行为使用,做些演示。

ServiceBehaviorAttribute & OperationBehaviorAttribute

这是两个最常用的行为控制特性,可用于控制:

  • 服务对象生命周期。
  • 并发管理。
  • 异步通讯。
  • 配置文件参数。
  • 事务。
  • 元数据转换。
  • 会话(Session)周期。
  • 等等...
[ServiceContract]
public interface ICalculate
{
  [OperationContract]
  int Add(int a, int b);
}

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class CalculateService : ICalculate
{
  public int Add(int a, int b)
  {
    Console.WriteLine(this.GetHashCode());
    return a + b;
  }
}

public class WcfTest
{
  public static void Test()
  {
    AppDomain.CreateDomain("Server").DoCallBack(delegate
    {
      ServiceHost host = new ServiceHost(typeof(CalculateService));
      host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(), "http://localhost:8080/calc");
      host.Open();
    });

    ChannelFactory<ICalculate> factory = new ChannelFactory<ICalculate>(new WSHttpBinding(),
      "http://localhost:8080/calc");

    ICalculate o = factory.CreateChannel();
    Console.WriteLine(o.Add(1, 2));
    Console.WriteLine(o.Add(1, 2));

    factory.Close();
  }
}


输出:
30136159
3
41153804
3

ServiceMetadataBehavior

用于开启元数据获取功能。只有使用该行为,客户端才能通过 Svcutil.exe 或其他工具获取服务信息,进而生成客户端代理文件。

ServiceHost host = new ServiceHost(typeof(CalculateService));
host.AddServiceEndpoint(typeof(ICalculate), new BasicHttpBinding(), "http://localhost:8080/calc");

ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri("http://localhost:8080/calc");
host.Description.Behaviors.Add(behavior);

host.Open();


ServiceDebugBehavior

开启调试功能,如将服务器端的异常信息直接传送给客户端。

ServiceHost host = new ServiceHost(typeof(CalculateService));
host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(), "http://localhost:8080/calc");
host.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
host.Open();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值