WCF openation实际应用异常解决方案

开发 开发工具
在WCF进行重载的时候,可能会出现一种本文介绍的异常出现。那么如何才能更好的解决问题呢?我们可以在WCF openation中加如一些操作即可。

WCF的实际应用方法多样化,要想全部掌握是一件非常困难的事情。不过我们可以在不断的实践中去积累应用经验,以帮助我们提高熟练应用程度。在这里就可以先学到一个WCF openation的应技巧。

很多时候我们用到方法的重载,在WCF中也不例外.不过需要加一点东西.我们以正常的方法来写一个方法的重载,代码如下:

  1. [ServiceContract]  
  2. public interface ICalculatorContract  
  3. {  
  4. [OperationContract]  
  5. int add(int x, int y);  
  6. [OperationContract]  
  7. double add(double x, double y);  

我把add方法进行了重载.

  1. public class CalculatorService:ICalculatorContract  
  2. {  
  3. #region ICalculatorContract Members  
  4. int ICalculatorContract.add(int x, int y)  
  5. {  
  6. return x + y;   
  7. }  
  8. #endregion  
  9. #region ICalculatorContract Members  
  10. public double add(double x, double y)  
  11. {  
  12. return x + y;   
  13. }  
  14. #endregion  

host 如下:

  1. BasicHttpBinding binding = new BasicHttpBinding();   
  2. Uri baseUri=new Uri ("http://172.28.3.45/CalculatorService");  
  3. ServiceHost host = new ServiceHost(typeof(CalculatorService), baseUri);   
  4. host.AddServiceEndpoint(typeof(ICalculatorContract), 
    binding,string.Empty);  
  5. ServiceMetadataBehavior behavior = host.Description.Behaviors.
    Find
    <ServiceMetadataBehavior>();  
  6. if (behavior == null)  
  7. {  
  8. behavior = new ServiceMetadataBehavior();  
  9. behavior.HttpGetEnabled = true;  
  10. behavior.HttpGetUrl = baseUri;  
  11. host.Description.Behaviors.Add(behavior);  
  12. }  
  13. host.Open(); 

这时我们运行host会出现异常:

Cannot have two operations in the same contract with the same name, methods add and add in type CalculatorContract.ICalculatorContract violate this rule. You can change the name of one of the operations by changing the method name or by using the Name property of OperationContractAttribute.

出现这个异常的原因是因为soap message action,不能区分这两个方法:所以解决如下:

  1. [ServiceContract]  
  2. public interface ICalculatorContract  
  3. {  
  4. [OperationContract(Name="add1")]  
  5. int add(int x, int y);  
  6. [OperationContract(Name="add2")]  
  7. double add(double x, double y);  

为WCF openation加一个***的name值.这样不可以soap message区分这两个方法了.再次运行host.没有异常了.

这样客户端就可以正常使用add方法.

【编辑推荐】

  1. MSMQ使用WCF正确实现技巧讲解
  2. WCF PreSession模式保持调用状态
  3. WCF PreCal模式基本代码示例解析
  4. WCF使用Nhibernate具体操作步骤图解
  5. WCF枚举实现技巧总结
责任编辑:曹凯 来源: 博客园
相关推荐

2010-02-26 15:46:48

Silverlight

2009-11-06 15:25:25

WCF异常

2010-02-25 14:53:44

WCF调用服务异常

2010-02-23 14:56:18

WCF Bug

2009-05-22 09:24:00

2010-02-22 10:29:11

WCF上传文件

2010-02-24 09:28:37

WCF安全配置

2010-04-30 17:33:27

Oracle数据集成

2009-12-07 15:50:27

WCF文件

2011-05-05 15:36:25

深信服广域网加速

2017-06-01 11:17:57

Python异常重试解决方案

2018-09-14 16:20:37

2010-03-01 13:06:49

WCF继承

2010-04-28 11:48:13

Oracle MySQ

2010-04-20 11:56:30

Oracle物理结构故

2010-07-13 16:36:07

SQLServer占内

2009-12-08 15:19:58

WCF大数据量

2009-11-05 12:45:25

WCF异常

2009-08-19 16:54:38

综合布线系统数据中心机柜

2020-09-04 13:50:35

前端异常监控代码
点赞
收藏

51CTO技术栈公众号