简体   繁体   中英

Return my object from WCF service.

I have application that host WCF service and I want to return this class object:

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:

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. maybe I need to configure my class in other way ? I have added [DataMember] to each member

LivePacketDevice and PacketDevice need to be [DataContract] s, while it might also work if they are just [Serializable] . Otherwise WCF does not know how to transfer them to the client.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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