wcfwebget

WCF WebGet and ICollection<>


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.


Solution

  • This should work:

    [ServiceKnownType(typeof(string[]))]
    [ServiceContract]
    public class WebConfigurationManager {
        [WebGet]
        [OperationContract]
        public ICollection<string> GetStrings() {
            return new string[] { "A", "B", "C" };
        }
    }