WCF行为控制实质内容简要概述

WCF开发插件的出现,给开发人员带来了非常不一样的体验。尤其是它独特的特点更是令开发人员眼前一亮。在这里先来了解一下WCF行为控制的基本内容。在完成服务契约设计和服务实现后,我们可以设置该服务的运行期行为(Behavior)。这些WCF行为控制包括 Service Behaviors、Endpoint Behaviors、Contract Behaviors、Operation Behaviors。#t#

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

WCF行为控制之ServiceBehaviorAttribute & OperationBehaviorAttribute

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

服务对象生命周期。

并发管理。

异步通讯。

配置文件参数。

事务。

元数据转换。

会话(Session)周期。

 
 
 
  1. [ServiceContract]
  2. public interface ICalculate
  3. {
  4. [OperationContract]
  5. int Add(int a, int b);
  6. }
  7. [ServiceBehavior(InstanceContextModeInstanceContextMode=
    InstanceContextMode.PerCall)]
  8. public class CalculateService : ICalculate
  9. {
  10. public int Add(int a, int b)
  11. {
  12. Console.WriteLine(this.GetHashCode());
  13. return a + b;
  14. }
  15. }
  16. public class WcfTest
  17. {
  18. public static void Test()
  19. {
  20. AppDomain.CreateDomain("Server").DoCallBack(delegate
  21. {
  22. ServiceHost host = new ServiceHost(typeof(CalculateService));
  23. host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(), 
    "http://localhost:8080/calc");
  24. host.Open();
  25. });
  26. ChannelFactory factory = new ChannelFactory
    (new WSHttpBinding(), 
  27. "http://localhost:8080/calc");
  28. ICalculate o = factory.CreateChannel();
  29. Console.WriteLine(o.Add(1, 2));
  30. Console.WriteLine(o.Add(1, 2));
  31. factory.Close();
  32. }
  33. }

输出:

 
 
 
  1. 30136159
  2. 3
  3. 41153804
  4. 3

WCF行为控制之ServiceMetadataBehavior

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

 
 
 
  1. ServiceHost host = new ServiceHost(typeof(CalculateService));
  2. host.AddServiceEndpoint(typeof(ICalculate), new BasicHttpBinding(),
     "http://localhost:8080/calc");
  3. ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  4. behavior.HttpGetEnabled = true;
  5. behavior.HttpGetUrl = new Uri("http://localhost:8080/calc");
  6. host.Description.Behaviors.Add(behavior);
  7. host.Open();

WCF行为控制之ServiceDebugBehavior

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

 
 
 
  1. ServiceHost host = new ServiceHost(typeof(CalculateService));
  2. host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(), 
    "http://localhost:8080/calc");
  3. host.Description.Behaviors.Find()
    .IncludeExceptionDetailInFaults = true;
  4. host.Open();

网页题目:WCF行为控制实质内容简要概述
分享URL:http://www.hantingmc.com/qtweb/news8/445308.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联