开发者

WCF: How do i return a .NET Framework class via Datacontract?

开发者 https://www.devze.com 2023-03-29 01:12 出处:网络
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:

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 clas开发者_运维技巧s seems easy. ;))


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:

[DataContract]
public sealed class CustomerResponse
{
    [DataMember]
    public Guid CustomerReference { get; set; }
}

[ServiceContract]
public interface IWcfMessagingService
{
    [OperationContract]
    CustomerResponse GetCustomer();
}

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.


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:

[Serializable]
public class MySearchResult
{
    public string Name { get; set; }

    public string Email { get; set; }
}

And simply iterate the searech results and pull out the properties you need like so:

var results = new List<MySearchResult>();

foreach (SearchResult r in searchResultCollection)
{
    results.Add(new MySearchResult
                    {
                        Name = searchResult.Properties["Name"],
                        Email = searchResult.Properties["Email"]
                    });
}

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消