WCF serialization ignores XmlRoot name with class implement IXmlSerializable

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 15:33:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33164766/wcf-serialization-ignores-xmlroot-name-with-class-implement-ixmlserializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!