Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

c# - Why can't I expose an interface in a .NET asmx web service?

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 {}

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

Cannot serialize member WidgetVersion1 of type IWidget because it is an interface.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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; }
}

...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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...