Skip to main content
 首页 » 编程设计

c#之使用通用对象从 web 服务方法返回数据

2024年01月12日27EasonJim

我有一个 ASMX 网络服务,其中包含许多将返回 XML 的方法。

该服务返回各种不同的对象,我创建了一个包装器对象,其中包含有关请求的信息,例如:

[Serializable] 
[XmlRoot("response")] 
public class DtoWrapper<T> 
{ 
    [XmlElement("error")] 
    public bool Error { get; set; } 
 
    [XmlElement("error_message")] 
    public string ErrorMessage { get; set; } 
 
    [XmlElement("success")] 
    public bool Success { get; set; } 
 
    [XmlElement("friendly_message")] 
    public string FriendlyMessage { get; set; } 
 
    [XmlArray("result")] 
    [XmlArrayItem("item")] 
    public List<T> Payload { get; set; } 
} 

现在一切正常,直到我用不同的类型定义了第二个方法。然后当我尝试加载 ASMX 测试页面时出现此错误

The top XML element 'response' from namespace 'http://tempuri.org/' references distinct types MyProject.Web.webservices.DtoWrapper1[MyProject.BusinessLogic.ClassA] and MyProject.Web.webservices.DtoWrapper1[MyProject.BusinessLogic.ClassB]. Use XML attributes to specify another XML name or namespace for the element or types.

我尝试用 [XmlType(Namespace="com.temp.A")] 和 [XmlType(Namespace="com.temp.B")] 标记我的对象 但它似乎没有帮助。

有什么想法吗?我是否必须为我想使用的每种类型创建一个包装器对象?

编辑:我意识到问题实际上不是类型参数。这是在类上指定了 [XmlRoot] 标记的事实。序列化程序将它们视为 2 种类型,但它们在同一命名空间中具有相同的根元素。

请您参考如下方法:

你不能这样做。 XML 没有泛型的概念,XML Schema 或 SOAP 也没有。就XML Schema而言,如果它具有相同的元素名称和相同的命名空间,那么它就是一回事。

您无法拥有通用的 Web 服务,因为这些概念不存在。