C# – web service can’t serialize an interface

c++interfaceserializationweb-services

I have an interface like so:

public interface IDocument : ISerializable
{
    Boolean HasBeenUploaded { get; set; }
    void ISerializable.GetObjectData(SerializationInfo, StreamingContext) { }
}

There are three documents that inherit from this, all of which serialize just fine. But when creating a simple web service, that does nothing, where they can be uploaded to…

public class DCService : System.Web.Services.WebService
{
    [WebMethod]
    public Boolean ReceiveDocument(IDocument document)
    {
        DBIO io = new DBIO();

        return io.InsertIntoDB(document); // does nothing; just returns true
    }
}

I get this when trying to run it: "Cannot serialize interface IDocument"

I'm not quite sure why this would be a problem. I know that some people have had trouble because they didn't want to force subclasses to implement custom serialization but I do, and up to this point it has been successful.

edit> If I create individual webmethods that accept the objects that implement the interface, it works fine, but that weakens the contract between the client/server (and undermines the purpose of having the interface in the first place)

Best Solution

You may need to use an XmlInclude attribute to your web method. A example can be found here. We have run into this issue before and have added XmlInclude attributes to both our web service proxy class on the client and to certain web service methods.

[WebMethod]
[XmlInclude(typeof(MyDocument))]
public Boolean ReceiveDocument(IDocument document)
{
    DBIO io = new DBIO();

    return io.InsertIntoDB(document); // does nothing; just returns true
}