简体   繁体   中英

WCF serialization ignores XmlRoot name with class implement IXmlSerializable

Here is my WCF service class:

class MyService : IMyService
{
   public String GetService(MyRequest request){...}
}

Here is the request class:

[XmlRoot("RequestClass")]
class MyRequest : IXmlSerializable
{
    public String Id {get;set;}
    public String ReqContent {get;set;}

    public void ReadXml(XmlReader reader)
    {
        using (XmlReader rr = reader.ReadSubtree())
        {
            Id = ...;
            ReqContent = ...;
        }
    }

    public void WriteXml(XmlWriter writer)
    {
       // write customize format content to the writer
    }
}

The serialization of MyRequest class was tested with below XmlSerializer instance:

    StringBuilder xml = new StringBuilder();
    XmlSerializer ser = new XmlSerializer(typeof(MyRequest), "");
    using (XmlWriter writer = XmlWriter.Create(xml))
    {
        ser.Serialize(writer, req);
    }

and got the xml as below:

<RequestClass>
   <Id>123</Id>
   <ReqContent>...</ReqContest>
</RequestClass>

Everything is fine here. However, after I applied the WCF service and pass the request class to the service, the xml got in the ReadXml is as below:

<request xmlns="http://tempuri.org/">
       <Id>123</Id>
       <ReqContent>...</ReqContest>
<request>

WCF serializer replace the root element of the class, how can I fix this issue?

Any idea is welcome and appreciated, I have trapped in this issue for several days.

PS1: I already read the post and have no idea how to fix this issue. PS2: I'm not sure if this was caused by the ClearUsernameBinding that I used in my project. If yes, how can I fix it without changing the binding?

I think everything is described in the post, you have mentioned in PS1. You should decide if your service is SOAP service or not. If it is, you can have full control over the message contract using message contract attributes, rather datacontract (which you actually don't use). If you want to have XML serialization you should add [XmlSerializerFormat] to the service contract. See DataContract XML serialization and XML attributes

For custom serialization you can also implement your own serializer and inject it into WCF pipeline using behaviors .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM