WCF WebGet and ICollection<>

血红的双手。 提交于 2019-12-24 00:45:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!