如何在wcf中返回包含嵌套类的类?

时间:2014-12-26 09:48:34

标签: c# web-services wcf wcf-binding

我有一个类MethodResponse。这是:

    [Serializable]
    [DataContract]
    public class MethodResponse
    {
        public enum ResponseType
        {
            Succeed,
            Error,
            NotValid,
            DataIsAlreadySaved
        };

        [DataMember]
        public ResponseType Type;

        [DataMember]
        public string ResultText;

        [DataMember]
        public object Object;


    }

我尝试从WCF返回MethodResponse。如果我不设置Object字段,但是当我设置Objet的值时,我可以返回它,它会返回这样的错误。

An error occurred while receiving the HTTP response to http://localhost:49601/CustomerService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

这是我的wcf和db类函数

           public MethodResponse GetCustomerById(int _id)
            {
                CustomerDb db = new CustomerDb();

                return db.GetCustomerById(_id);
            }

           public MethodResponse GetCustomerById(int _id)
            {
                try
                {
                    MethodResponse mrMethodResponse = new MethodResponse();

                    using (var contex = new TestEntities())
                    {

                        contex.Configuration.LazyLoadingEnabled = false;
                        Customer customer = contex.Customers.FirstOrDefault(cstm => cstm.id == _id);
                                 mrMethodResponse.Type = MethodResponse.ResponseType.Succeed;
                        mrMethodResponse.Type = MethodResponse.ResponseType.Succeed;
                       mrMethodResponse.Object = customer;


                        return mrMethodResponse;
                    }


                }
                catch (Exception)
                {

                    throw;
                }
            }

1 个答案:

答案 0 :(得分:1)

您的问题是您尝试返回object。不允许这样做。您应该指定具体的类或泛型类型。

更改属性类型
    [DataMember]
    public object Object;

    [DataMember]
    public Customer Object;

您还必须确保Customer类可序列化。