WCF WebGet and ICollection<>

2019-07-13 13:39发布

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.

标签: wcf webget
2条回答
该账号已被封号
2楼-- · 2019-07-13 14:17

Andrew pointed me in the right direction. The answer is to add

[ServiceKnownType(typeof(string[]))]

above the [ServiceContract] attribute.

查看更多
姐就是有狂的资本
3楼-- · 2019-07-13 14:26

This should work:

[ServiceKnownType(typeof(string[]))]
[ServiceContract]
public class WebConfigurationManager {
    [WebGet]
    [OperationContract]
    public ICollection<string> GetStrings() {
        return new string[] { "A", "B", "C" };
    }
}
查看更多
登录 后发表回答