问题
I'm attempting to return a generic ICollection from a REST WCF service. Should the following be possible?
[ServiceContract]
public class WebConfigurationManager {
[WebGet]
[OperationContract]
public ICollection<string> GetStrings() {
return new string[] { "A", "B", "C" };
}
}
When I attempt to execute this operation from my web browser, I get an error. Looking through my WCF trace shows me this:
Cannot serialize parameter of type 'System.String[]' (for operation 'GetStrings', contract 'WebConfigurationManager') because it is not the exact type 'System.Collections.Generic.ICollection`1[System.String]' in the method signature and is not in the known types collection. In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute.
回答1:
This should work:
[ServiceKnownType(typeof(string[]))]
[ServiceContract]
public class WebConfigurationManager {
[WebGet]
[OperationContract]
public ICollection<string> GetStrings() {
return new string[] { "A", "B", "C" };
}
}
回答2:
Andrew pointed me in the right direction. The answer is to add
[ServiceKnownType(typeof(string[]))]
above the [ServiceContract] attribute.
来源:https://stackoverflow.com/questions/1139834/wcf-webget-and-icollection