简体   繁体   English

从WCF服务返回我的对象​​。

[英]Return my object from WCF service.

I have application that host WCF service and I want to return this class object: 我有承载WCF service应用程序,并且我想返回此类对象:

namespace classes
{
    [DataContract]
    public class NetworkAdapter
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string ID { get; set; }
        [DataMember]
        public string Description { get; set; }
        [DataMember]
        public string IPAddress { get; set; }
        [DataMember]
        private string gatewayIpAddress;
        [DataMember]
        public string Speed { get; set; }
        [DataMember]
        public string NetworkInterfaceType { get; set; }
        [DataMember]
        public string MacAddress { get; set; }
        [DataMember]
        private LivePacketDevice livePacketDevice;
        [DataMember]
        public PacketDevice PacketDevice { get { return livePacketDevice; } }

        public NetworkAdapter(LivePacketDevice packetDevice)
        {
            livePacketDevice = packetDevice;
        }

        public override string ToString()
        {
            return Description;
        }

        public static NetworkAdapter[] getAll()
        {
            List<NetworkAdapter> list = new List<NetworkAdapter>();
            foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
                foreach (UnicastIPAddressInformation uniCast in adapter.GetIPProperties().UnicastAddresses)
                {
                    if (!System.Net.IPAddress.IsLoopback(uniCast.Address) && uniCast.Address.AddressFamily != AddressFamily.InterNetworkV6)
                    {
                        StringBuilder gatewayIPAddresses = new StringBuilder();
                        string gatewayIPAddressesDisplay = string.Empty;
                        foreach (var address in adapter.GetIPProperties().GatewayAddresses)
                        {
                            gatewayIPAddresses.Append(address.Address);
                            gatewayIPAddresses.Append(" ");
                        }

                        if (gatewayIPAddresses.Length > 0)
                        {
                            gatewayIPAddressesDisplay = gatewayIPAddresses.ToString().TrimEnd(' ');
                        }

                        if (!list.Any(l => l.ID == adapter.Id))
                        {
                            list.Add(new NetworkAdapter(getDevice(adapter.Id))
                            {
                                Name = adapter.Name,
                                ID = adapter.Id,
                                Description = adapter.Description,
                                IPAddress = uniCast.Address.ToString(),
                                NetworkInterfaceType = adapter.NetworkInterfaceType.ToString(),
                                Speed = adapter.Speed.ToString("#,##0"),
                                MacAddress = getMacAddress(adapter.GetPhysicalAddress().ToString()),
                                gatewayIpAddress = gatewayIPAddressesDisplay
                            });
                        }
                    }
                }

            //return list.GroupBy(n => n.ID).Select(g => g.FirstOrDefault()).ToArray();
            return list.ToArray();
        }

        private static LivePacketDevice getDevice(string id)
        {
            return LivePacketDevice.AllLocalMachine.First(x => x.Name.Contains(id));
        }

        private static string getMacAddress(string oldMAC)
        {
            int count = 0;
            string newMAC = oldMAC;

            for (int i = 2; i < oldMAC.Length; i += 2)
            {
                newMAC = newMAC.Insert(i + count++, ":");
            }

            return newMAC;
        }

        public string defaultGateway
        {
            get
            {
                if (gatewayIpAddress != "")
                {
                    return gatewayIpAddress;
                }

                return "n/a";
            }
        }

        private static string getIpFourthSegment(string ipAddress)
        {
            try
            {
                string[] arr = ipAddress.Split('.');
                return arr[3];
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}

This is my service: 这是我的服务:

[ServiceContract()]
public interface IService1
{
    [OperationContract]
    NetworkAdapter[] GetAdapters();

    [OperationContract]
    string GetDate();
}

[ServiceBehavior(
    ConcurrencyMode = ConcurrencyMode.Multiple,
    InstanceContextMode = InstanceContextMode.PerSession)]

public class service1 : IService1
{
    public NetworkAdapter[] GetAdapters()
    {
        IEnumerable<NetworkAdapter> adapters = NetworkAdapter.getAll();
        return adapters.ToArray();
    }

    public string GetDate()
    {
        return DateTime.Now.ToString();
    }
}

When I am try to run GetAdapters function got this error: 当我尝试运行GetAdapters函数时收到此错误:

An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll

Additional information: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9599960'.

When try to run GetDate function it works fine and return simple string. 尝试运行GetDate函数时,它可以正常工作并返回简单的字符串。 maybe I need to configure my class in other way ? 也许我需要以其他方式配置班级? I have added [DataMember] to each member 我已经为每个成员添加了[DataMember]

LivePacketDevice and PacketDevice need to be [DataContract] s, while it might also work if they are just [Serializable] . LivePacketDevicePacketDevice必须为[DataContract] ,但是如果它们只是[Serializable]也可能起作用。 Otherwise WCF does not know how to transfer them to the client. 否则,WCF不知道如何将它们传输到客户端。

Also it is advisable to only transfer objects that just hold data, not functionality, as that functionality will not be available to the client. 另外,建议仅传输仅保存数据的对象,而不传输功能,因为该功能对于客户端将不可用。 The stub created on the client side will only contain data fields, not methods, as code is not transferred/cloned. 在客户端创建的存根将仅包含数据字段,而不包含方法,因为代码不会被传输/克隆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM