ASP.NET:从Web Service方法返回对象列表

时间:2014-05-11 06:39:16

标签: c# asp.net web-services serialization business-logic-layer

我想知道如何返回对象列表而不是字符串列表?

返回一个字符串列表有效,但是当我用一个对象替换所有字符串时它会失败..

这是我的Web服务

[WebMethod]
 public List<OpProduct> SearchProduct(string name) {
   BLProduct blProduct = new BLProduct();
   List<OpProduct> result = byproduct.SearchProducts(name);

   return result;
}

这是我的业务逻辑层

public List<OpProduct> SearchProducts(string name)
{
  List<OpProduct> result = (from item in db.OpProducts where item.Name.StartsWith(name) select item).ToList<OpProduct>();

  return result;
}

这是我的错误消息(抱歉,无法翻译)

  

System.InvalidOperationException:Er是een fout opgetreden bij het   genereren van het XML-document。 ---&GT; System.InvalidOperationException:   呃是kenverwijzing aangetroffen tijdens het toepassen van   serialisatie op een object van het type OpProduct。 BIJ   System.Xml.Serialization.XmlSerializationWriter.WriteStartElement(字符串   name,String ns,Object o,Boolean writePrefixed,   XmlSerializerNamespaces xmlns)bij   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write9_OpProduct(字符串   n,String ns,OpProduct o,Boolean isNullable,Boolean needType)
  BIJ   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write5_OpGeheugen(字符串   n,String ns,OpGeheugen o,Boolean isNullable,Boolean needType)
  BIJ   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write9_OpProduct(字符串   n,String ns,OpProduct o,Boolean isNullable,Boolean needType)
  BIJ   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write10_ArrayOfOpProduct(对象   o)bij   Microsoft.Xml.Serialization.GeneratedAssembly.ListOfOpProductSerializer.Serialize(对象   objectToSerialize,XmlSerializationWriter writer)bij   System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter,   Object o,XmlSerializerNamespaces名称空间,String encodingStyle,   String id)--- Einde van intern uitzonderingsstackpad --- bij   System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter,   Object o,XmlSerializerNamespaces名称空间,String encodingStyle,   字符串id)bij   System.Xml.Serialization.XmlSerializer.Serialize(的TextWriter   textWriter,Object o,XmlSerializerNamespaces namespaces)bij   System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse对象   response,Stream outputStream,Object returnValue)bij   System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(对象[]   returnValues,Stream outputStream)bij   System.Web.Services.Protocols.WebServiceHandler.WriteReturns(对象[]   returnValues)bij   System.Web.Services.Protocols.WebServiceHandler.Invoke()

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

默认情况下,只有系统原语类型和这些基本类型的数组(如int,float,double,string)可用作返回值。

如果要将自己的类用作参数,则必须使用XML定义将它们定义为复杂类型。这是关于此的MSDN链接 https://msdn.microsoft.com/en-us/library/aa480498.aspx