WCF 序列化使用类实现 IXmlSerializable 忽略 XmlRoot 名称 [英] WCF serialization ignores XmlRoot name with class implement IXmlSerializable

查看:25
本文介绍了WCF 序列化使用类实现 IXmlSerializable 忽略 XmlRoot 名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 WCF 服务类:

Here is my WCF service class:

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

这是请求类:

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

MyRequest 类的序列化使用以下 XmlSerializer 实例进行了测试:

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

并得到如下的xml:

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

这里一切正常.但是,当我应用WCF服务并将请求类传递给该服务后,ReadXml中得到的xml如下:

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 序列化器替换了类的根元素,我该如何解决这个问题?

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:我已经阅读了 post 并且不知道如何解决这个问题.PS2:我不确定这是否是由 ClearUsernameBinding 我在我的项目中使用的.如果是,如何在不更改绑定的情况下修复它?

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?

推荐答案

我觉得帖子里都有描述,你在 PS1 里也提到过.您应该决定您的服务是否是 SOAP 服务.如果是,您可以使用消息合同属性而不是数据合同(您实际上不使用)完全控制消息合同.如果您想进行 XML 序列化,您应该将 [XmlSerializerFormat] 添加到服务合同中.请参阅 DataContract XML 序列化和 XML 属性

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

对于自定义序列化,您还可以实现您自己的序列化程序并注入它使用行为进入 WCF 管道.

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

这篇关于WCF 序列化使用类实现 IXmlSerializable 忽略 XmlRoot 名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆