2011-04-22

WCF Service无法取同名方法

Posted in .NET at 13:06 Author:仲远

标签:

在WCF中,如果你进行函数重载,会发现在部署时提示“Cannot have two operations in the same contract with the same name”的错误。解决办法是在OperationContract之后添加一个“别名”:(Name = “XXXXXXXXXXX”)。这样在代码中可以实现函数重载。不过从Client的角度来看,就是看到使用别名之后的新函数了。

以下为转载:

In our introductory WCF tutorial, I created a basic service contract that accepted a string and returned a reversed version of it. For this tutorial, I want to overload this function to also accept a character array. If I were to attempt to just stick in my overload like this:

[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
[OperationContract]
string ReverseString(char[] value);
}

It would result in this exception being thrown at runtime:

Cannot have two operations in the same contract with the same name, methods ReverseString and ReverseString in type WCFServer.IStringReverser 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.

By default, every operation contract gets a name that is set to the name of method. In WCF, you cannot have two operation contracts with the same name. Fortunately, this is very easy to fix by simply setting the name property of the operation contract attribute.

[ServiceContract]
public interface IStringReverser
{
[OperationContract(Name = “ReverseStringFromString”)]
string ReverseString(string value);
[OperationContract(Name = “ReverseStringFromCharArray”)]
string ReverseString(char[] value);
}

And there you have it. We now have a WCF service contract with overloaded methods.

本文可以自由转载,转载时请保留全文并注明出处:
转载自仲子说 [ http://www.wangzhongyuan.com/ ]
原文链接:

Leave a Comment

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word