为什么我不能暴露在.NET ASMX的Web服务的接口?接口、NET、ASMX、Web

2023-09-03 01:28:49 作者:可爱到不行

我有一个.NET Web服务(使用ASMX ...还没有升级到WCF还),公开以下内容:

I have a .NET web service (using asmx...have not upgraded to WCF yet) that exposes the following:

public class WidgetVersion1 : IWidget {}
public class WidgetVersion2 : IWidget {}

当我尝试绑定到Web服务,我得到以下序列化错误:

When I attempt to bind to the web service, I get the following serialization error:

无法序列类型的iWidget成员WidgetVersion1,因为它是一个接口。

我曾尝试添加各种属性,在iWidget接口( XmlIgnore SoapIgnore 非序列化),但它们是无效的接口上。​​

I have tried adding various attributes to the IWidget interface (XmlIgnore, SoapIgnore, NonSerialized), but they are not valid on an interface.

有谁知道为什么我不能公开接口?我认为WSDL不支持的接口,但不能.NET围绕这根本就不是序列化的界面?围绕这个有什么方法除了从WidgetVersion1和WidgetVersion2类定义?

Does anyone know why I am unable to expose the interface? I assume WSDL does not support interfaces, but couldn't .NET get around this by simply not serializing the interface? Are there any ways around this apart from removing the IWidget interface from the WidgetVersion1 and WidgetVersion2 class definitions?

推荐答案

WCF不能序列接口要么;事实上,这是不可能的序列通过SOAP接口。

WCF can't serialize an interface either; in fact, it's impossible to serialize an interface over SOAP.

原因(简体)是,当反序列化的,.NET必须能够创造出一些实际的具体类。接口是一个抽象的概念;那里总是要成为一个背后的真正的类实现,以便实际情况存在。

The reason (simplified) is that, when deserializing, .NET has to be able to create some actual concrete class. An interface is an abstract concept; there always has to be a "real" class implementation behind it in order for an actual instance to exist.

既然你不能构造一个接口的物理实例,它也不可能被序列化。

Since you can't construct a physical instance of an interface, it also can't be serialized.

如果你想使用 XmlIgnoreAttribute ,明白,把它应用到的键入的将一事无成。它需要的,而不是应用到的成员。换句话说:

If you're trying to use the XmlIgnoreAttribute, understand that applying it to the type won't accomplish anything. It needs to be applied to the member instead. In other words:

public class SerializableClass
{
    [XmlElement]
    public int ID { get; set; }

    [XmlElement]
    public string Name { get; set; }

    [XmlIgnore]
    public IMyInterface Intf { get; set; }
}

...将系列化确定,因为串行不会尝试序列化 INTF 属性。你就不能添加 [XmlIgnore] 属性添加到 IMyInterface的类型定义(它不会编译)。

...will serialize OK, because the serializer won't try to serialize the Intf property. You just can't add the [XmlIgnore] attribute to the IMyInterface type definition (it won't compile).