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

时间:2014-02-17 11:37:21

标签: c# wcf

我有托管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;
            }
        }
    }
}

这是我的服务:

[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();
    }
}

当我尝试运行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'.

当尝试运行GetDate函数时,它工作正常并返回简单的字符串。 也许我需要以其他方式配置我的课程?我已将[DataMember]添加到每个成员

1 个答案:

答案 0 :(得分:0)

LivePacketDevicePacketDevice需要[DataContract],而如果它们只是[Serializable],它也可能有用。否则WCF不知道如何将它们传输到客户端。

此外,建议仅传输仅保存数据的对象,而不是功能,因为客户端无法使用该功能。在客户端创建的存根将只包含数据字段,而不包含方法,因为代码不会被传输/克隆。