WCF:如何通过数据契约返回 .NET Framework 类?
作为 WCF 的初学者,我想实现对 Active Directory 服务的调用,该服务获取所有用户,该方法如下所示:
[OperationContract]
SearchResultCollection GetAllUsers();
SearchResultCollection 不可序列化,因此我必须执行如下操作:
[DataContract] SearchResultCollection
因此,我必须创建自己的包装类,它继承 SearchResultCollection 或使用 IDataContractSerializer。这两种解决方案似乎都不容易。
问题:如何使用 .NET 类作为 WCF 服务中的返回类型的“标准”方法?
(为我自己的类编写自己的 DataContract 似乎很容易。;))
As a beginner to WCF i want to implement a call to the Active Directory Service which gets all Users, the method looks like this:
[OperationContract]
SearchResultCollection GetAllUsers();
SearchResultCollection is not serializable so i have to make something like this:
[DataContract]
SearchResultCollection
So i have to make my own wrapper class which inherits the SearchResultCollection or use IDataContractSerializer. Both solutions seems not easy.
The question: How is the "standard" approach to use .NET Classes as a return type in a WCF service?
(Writing a own DataContract for my own class seems easy. ;))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DataContract
路由在这里就足够了。标准方法是用相关属性装饰您的类,并且 WCF 可以在方法中使用它:如果该类不可序列化,我认为即使包装它也不起作用。
但是,
SearchResultCollection
本身是从 WCF 方法返回的,因此您可以直接通过您自己的服务传递它,或者至少成功包装它。The
DataContract
route will suffice here. The standard way is to decorate your class with the relevant attributes and it will be consumable by WCF in methods:If the class is not serializable, I don't think even wrapping it will work.
However, the
SearchResultCollection
is itself returned from a WCF method, so you could just pass that straight through your own service, or at the very least, wrap it successfully.我认为最好的选择是创建自己的简单 POCO 类来表示 SearchResult,并返回这些对象的列表。实际上,您希望能够准确控制需要从服务发回的信息。例如:
只需迭代搜索结果并提取您需要的属性,如下所示:
这样,发送回的 xml 就不会因为您不需要的所有属性而变得臃肿,并且您可以序列化自己的
List
List< MySearchResult>
返回结果。顺便说一句,我不知道名称和电子邮件属性是否存在,我只是展示一个示例。I think your best bet is create your own simple POCO class to represent
SearchResult
, and return a list of these objects. Really you want to be able to control exactly the information you need to send back from the service. For example:And simply iterate the searech results and pull out the properties you need like so:
That way the xml being sent back isn't bloated with all the properties you don't need AND you can serialize your own
List<MySearchResult>
return results. And by the way I have no idea if the Name and Email properties exist I am just showing an example.我想我只会返回一个用户列表,其中用户是标记为可序列化的自定义用户类。从活动目录获取数据的方法可以通过循环结果来填充 User 类。
I think I would just return a List of User where User is a custom User class flagged as Serializable. The method that gets the data from active directory can populate the User class by looping through the result.