新聞中心
WCF的實際應(yīng)用方法多樣化,要想全部掌握是一件非常困難的事情。不過我們可以在不斷的實踐中去積累應(yīng)用經(jīng)驗,以幫助我們提高熟練應(yīng)用程度。在這里就可以先學(xué)到一個WCF openation的應(yīng)技巧。

很多時候我們用到方法的重載,在WCF中也不例外.不過需要加一點東西.我們以正常的方法來寫一個方法的重載,代碼如下:
- [ServiceContract]
- public interface ICalculatorContract
- {
- [OperationContract]
- int add(int x, int y);
- [OperationContract]
- double add(double x, double y);
- }
我把add方法進行了重載.
- public class CalculatorService:ICalculatorContract
- {
- #region ICalculatorContract Members
- int ICalculatorContract.add(int x, int y)
- {
- return x + y;
- }
- #endregion
- #region ICalculatorContract Members
- public double add(double x, double y)
- {
- return x + y;
- }
- #endregion
- }
host 如下:
- BasicHttpBinding binding = new BasicHttpBinding();
- Uri baseUri=new Uri ("http://172.28.3.45/CalculatorService");
- ServiceHost host = new ServiceHost(typeof(CalculatorService), baseUri);
- host.AddServiceEndpoint(typeof(ICalculatorContract),
binding,string.Empty);- ServiceMetadataBehavior behavior = host.Description.Behaviors.
Find(); - if (behavior == null)
- {
- behavior = new ServiceMetadataBehavior();
- behavior.HttpGetEnabled = true;
- behavior.HttpGetUrl = baseUri;
- host.Description.Behaviors.Add(behavior);
- }
- host.Open();
這時我們運行host會出現(xiàn)異常:
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.
出現(xiàn)這個異常的原因是因為soap message action,不能區(qū)分這兩個方法:所以解決如下:
- [ServiceContract]
- public interface ICalculatorContract
- {
- [OperationContract(Name="add1")]
- int add(int x, int y);
- [OperationContract(Name="add2")]
- double add(double x, double y);
- }
為WCF openation加一個***的name值.這樣不可以soap message區(qū)分這兩個方法了.再次運行host.沒有異常了.
這樣客戶端就可以正常使用add方法.
【編輯推薦】
- MSMQ使用WCF正確實現(xiàn)技巧講解
- WCF PreSession模式保持調(diào)用狀態(tài)
- WCF PreCal模式基本代碼示例解析
- WCF使用Nhibernate具體操作步驟圖解
- WCF枚舉實現(xiàn)技巧總結(jié)
當前文章:WCFopenation實際應(yīng)用異常解決方案
分享路徑:http://m.5511xx.com/article/dpjecjs.html


咨詢
建站咨詢
